0
0
Cprogramming~5 mins

Return values in C

Choose your learning style9 modes available
Introduction

Return values let a function send back a result to the part of the program that called it. This helps reuse code and get answers from functions.

When you want a function to calculate a number and give it back.
When you need to check if a task succeeded or failed inside a function.
When you want to get a value from a function to use somewhere else.
When you want to break a big problem into smaller parts and get results from each part.
Syntax
C
return expression;

The return keyword sends the value of expression back to the caller.

Functions that return a value must have a matching return type in their declaration.

Examples
Returns the number 5 to the caller.
C
return 5;
Returns the sum of variables x and y.
C
return x + y;
Used in functions with void return type to exit the function early without returning a value.
C
return;
Sample Program

This program defines a function add that returns the sum of two numbers. The main function calls add and prints the returned result.

C
#include <stdio.h>

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

int main() {
    int result = add(3, 4);
    printf("The sum is %d\n", result);
    return 0;
}
OutputSuccess
Important Notes

Once a return statement runs, the function stops immediately.

Functions declared with void do not return a value but can use return; to exit early.

Summary

Use return to send a value back from a function.

The return type of the function must match the type of the returned value.

Returning values helps break problems into smaller, reusable parts.