Return Values
Functions in C can send back a value to the code that called them. This is called a return value.
Function Return Types
Every function in C has a return type that specifies what kind of value it will return:
int add(int a, int b) {
return a + b; // Returns an integer
}
float divide(float x, float y) {
return x / y; // Returns a float
}
char getGrade(int score) {
if (score >= 90) return 'A';
else if (score >= 80) return 'B';
else return 'C'; // Returns a character
}
The return Statement
The return statement is used to send a value back from a function:
#include <stdio.h>
int multiply(int x, int y) {
int result = x * y;
return result; // Send back the result
}
int main() {
int answer = multiply(5, 3); // answer gets the value 15
printf("5 x 3 = %d\n", answer);
return 0;
}
Functions Without Return Values (void)
Some functions don't need to return anything - they just perform an action. These use the void return type:
void printMessage() {
printf("Hello, World!\n");
// No return statement needed (or just 'return;')
}
void displayMenu() {
printf("1. Start Game\n");
printf("2. Settings\n");
printf("3. Exit\n");
return; // Optional for void functions
}
Using Return Values
You can use return values in different ways:
#include <stdio.h>
int square(int num) {
return num * num;
}
int main() {
// Store in a variable
int result = square(4);
printf("Square of 4 is %d\n", result);
// Use directly in expressions
int sum = square(3) + square(4); // 9 + 16 = 25
printf("Sum of squares: %d\n", sum);
// Use in conditions
if (square(5) > 20) {
printf("25 is greater than 20!\n");
}
return 0;
}
Multiple Return Statements
A function can have multiple return statements, but only one will execute:
int findMax(int a, int b) {
if (a > b) {
return a; // Exit here if a is larger
}
return b; // Exit here if b is larger or equal
}
char checkSign(int number) {
if (number > 0) return '+';
if (number < 0) return '-';
return '0'; // number is zero
}
Important Notes
- Once a
returnstatement executes, the function immediately exits - The returned value must match the function's return type
main()function typically returns 0 to indicate successful program execution- If a non-void function doesn't return a value, the behavior is undefined