In C programming, the return
statement is used to exit from a function and optionally return a value to the calling function. The behavior of the return
statement varies depending on whether the function is a void function (which doesn’t return a value) or a non-void function (which returns a value).
Syntax of the return statement:
return expression;
Where:
- expression is the value you want to return from the function. The type of the expression must match the return type declared for the function.
Types of functions and their return statements:
- Void Function: A function with the
void
return type does not return any value. Thereturn
statement is used simply to exit the function.void example() { printf("This is a void function.\n"); return; // Optional, as control will exit the function automatically at the end }
- Non-void Function (Returns a Value): A function that returns a value must include a
return
statement that provides a value matching the declared return type.int add(int a, int b) { return a + b; // Return the sum of a and b } int main() { int result = add(5, 3); printf("The sum is %d\n", result); return 0; // Return value to indicate successful program termination }
Key Points:
- Returning from a Function: When the
return
statement is executed, control is transferred back to the point where the function was called. - Function Return Type: If the function is declared with a return type other than
void
, you must return a value of that type. If the function isvoid
, no value is returned. - Exiting Early: The
return
statement can be used to exit from a function before reaching the end, which can be useful for error handling or early termination based on certain conditions.
Example with Condition:
int find_max(int a, int b) {
if (a > b) {
return a; // Return a if it is greater than b
} else {
return b; // Otherwise return b
}
}
int main() {
int max_value = find_max(10, 20);
printf("The maximum value is %d\n", max_value);
return 0;
}
This example demonstrates the use of the return
statement based on a condition inside the function.