CodeBlanks Logo Icon CodeBlanks

Return values

Learn to return a value from a function with return.

Returning values with return

A function can send a value back to the caller with the return keyword. The return type sets the type of the value.

int add(int a, int b) {
    return a + b;
}

int result = add(3, 5);  /* result = 8 */

When return runs, the function ends and the value goes back to the caller. void functions return no value; they can only early-exit with return;.

Using the return value

You can assign a function's return value to a variable or use it directly in an expression.

int result = add(3, 5);
printf("%d\n", add(2, 4));  /* prints 6 */
int bigger = add(1, 1) > add(0, 0);

It is also fine to ignore the value: add(3, 5); computes the result but does not store it. If the function has side effects (like printf), this still matters.

Practice Square of a number

Define int square(int x) with body return x * x;. Call printf("%d\n", square(4)); from main. Output should be 16.

Starter code

main.c
#include <stdio.h>

/* define square function */

int main(void) {
    /* call printf %d with square(4) */
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int square(int x) {
    return x * x;
}

int main(void) {
    printf("%d\n", square(4));
    return 0;
}

Expected output

16

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 return expression

Question
int square(int x) {
    return ____;
}
Answer
int square(int x) {
    return x * x;
}

Explanation: Answer is x * x. The square is x times x.

2 Which return statement can a void function use?

  • return 5;
  • return x + y;
  • return; Correct answer
  • return "text";

Explanation: A void function can only early-exit with return;.

3 Match return types

Term Meaning
int returns integer
void no return value
char returns character
double returns decimal

All lessons in Beginner