In C, functions can return a value to the caller. The return type specifies what type of data the function will return, such as int
, float
, or void
. Functions may also return nothing, which is represented by the void
return type.
The syntax for declaring a return type is placed before the function name. It indicates the data type of the value the function will return.
return_type function_name() { // Function body return value; // Return statement with the appropriate data type }
Here, return_type
specifies the data type, and value
is the value the function returns to the caller.
#include// Function that returns an integer int add(int a, int b) { return a + b; // Returning the sum of a and b } int main() { int sum = add(5, 3); // Storing the returned value printf("Sum: %d\n", sum); // Output will be 8 return 0; }
add()
returns the sum of two integers. The returned value is then stored in sum
and printed in main()
.
#include// Function that returns a float float average(float x, float y) { return (x + y) / 2; // Returning the average of x and y } int main() { float avg = average(5.0, 3.0); // Storing the returned value printf("Average: %.2f\n", avg); // Output will be 4.00 return 0; }
average()
returns the average of two float numbers. The returned value is stored in avg
and printed in main()
.
void
#include// Function that doesn't return a value void displayMessage() { printf("Hello, world!\n"); // Prints a message } int main() { displayMessage(); // Calling the function without expecting a return value return 0; }
displayMessage()
has a void
return type, meaning it doesn't return any value. It simply prints a message to the console.
int
, float
, or void
).void
return type, it must return a value of that type using the return
keyword.void
, it does not return any value, and the return
statement is optional (though you can use it to exit early from the function).#include// Function that returns a string (character array) char* greet() { return "Hello, C Programmer!"; } int main() { printf("%s\n", greet()); // Calling the function and printing the returned string return 0; }
greet()
returns a string, and in the main()
function, this string is printed to the console.
main()
and store the result.void
return type and uses return
to exit the function early.return
keyword when the function's return type is non-void
.int
from a function declared to return float
.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!