Return values from functions in C language
After completing its duty, a function in the C programming language can also return a value. A function must have a return type stated in its declaration, which details the kind of value the function will return, in order to return a value.
Syntax:
return_type function_name(parameter_list) {
// function body
return value;
}
Here, return_type specifies the data type of the value that the function will return, function_name is the name of the function, and parameter_list is a comma-separated list of parameters that the function can accept. The function body contains the statements that define the task to be performed by the function. The return statement is used to return a value from the function.
Example:
#include <stdio.h>
void rectangle_info(int length, int width, int *area, int *perimeter) {
*area = length * width;
*perimeter = 2 * (length + width);
}
int main() {
int length = 5;
int width = 3;
int area, perimeter;
rectangle_info(length, width, &area, &perimeter);
printf("Length: %d\n", length);
printf("Width: %d\n", width);
printf("Area: %d\n", area);
printf("Perimeter: %d\n", perimeter);
return 0;
}
Output:
Length: 5
Width: 3
Area: 15
Perimeter: 16
Example 2:
#include <stdio.h>
int find_max_index(int arr[], int size) {
int max = arr[0];
int max_index = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
max_index = i;
}
}
return max_index;
}
int main() {
int arr[] = {3, 7, 2, 8, 1, 9, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
int max_index = find_max_index(arr, size);
printf("The maximum value in the array is %d, found at index %d\n", arr[max_index], max_index);
return 0;
}
Output:
The maximum value in the array is 9, found at index 5