A function can return a computed value to its caller using the return statement. When multiple values need to be provided, a function can return a structure, or write results into caller-provided objects through pointers.
#include <stdio.h>
int calculateSum(int a, int b)
{
return a + b;
}
double calculateArea(double length, double width)
{
return length * width;
}
int main(void)
{
int sum = calculateSum(10, 20);
double area = calculateArea(5.0, 3.0);
printf("Sum = %d\n", sum);
printf("Area = %.2f\n", area);
return 0;
}
Example Output #
Sum = 30
Area = 15.00
Explanation #
The function calculateSum() returns an integer:
return a + b;
The calling code receives the value and stores it in sum.
The function calculateArea() returns a double:
return length * width;
Its return value is stored in area.
Ways to Return Data #
| Method | Example | Description |
|---|---|---|
| Return a scalar value | return a + b; |
Returns one value of the specified type |
| Return a structure | return result; |
Returns a structure value containing multiple fields |
| Use output parameters | calculate(&sum, &product); |
Writes results into caller-provided objects |
| Return a pointer | return ptr; |
Returns an address, provided the pointed-to object remains valid |
A function cannot return an array type directly in C. To return array-related data, use a pointer to valid storage, a structure containing an array, or a caller-provided output array. The lifetime of the underlying storage must be considered when returning pointers.