In C, a function can return a value back to the caller using the return
statement. The return type is specified before the function name in the declaration and definition.
πΉ What is a Return Value?
A return value is the output a function sends back after it completes. This allows the calling code to use that result in further operations.
π Example 1: Function Returning an Integer
This function adds two numbers and returns the result.
#include <stdio.h> int add(int a, int b); // Function declaration int main() { int sum = add(4, 6); // Store the return value printf("Sum: %d\n", sum); return 0; } int add(int a, int b) { return a + b; // Return the result }
π Example 2: Returning a Float
This function divides two numbers and returns a floating-point result.
#include <stdio.h> float divide(int x, int y); // Function declaration int main() { float result = divide(10, 3); printf("Result: %.2f\n", result); return 0; } float divide(int x, int y) { return (float)x / y; // Typecast to float }
π Example 3: Function Returning Nothing (void)
If a function doesn’t need to return anything, use void
as its return type.
#include <stdio.h> void greet(); // Declaration int main() { greet(); // Just call, no return value return 0; } void greet() { printf("Hello, World!\n"); }
π― Summary
- Use
return
to send values back from a function. - Return type must match the value being returned.
void
functions donβt return anything.- Returned values can be stored in variables or used directly in expressions.
π‘ Try It Yourself
Change the return type, return different data, or try chaining function calls. Return values make your functions truly powerful and reusable!