C Return Values
In this page:
The return Statement
The return statement immediately ends a function's execution and, if the function has a non-void return type, sends a value back to whatever code called it -- any statements after return in that function never run.
Example: The return Statement
#include <stdio.h>
int getFive() {
return 5;
printf("never runs");
}
int main() {
printf("%d", getFive());
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Returning Integers
Declaring a function's return type as int means it hands back a whole number to its caller, which is the standard choice for functions computing counts, indexes, or results of integer arithmetic.
Example: Returning Integers
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
printf("%d", add(2, 3));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Returning Floating-Point Numbers
When a calculation needs fractional precision, declaring the function's return type as float or double lets it hand back a decimal result instead of being forced to round to a whole number.
Example: Returning Floating-Point Numbers
#include <stdio.h>
double divide(int a, int b) {
return (double)a / b;
}
int main() {
printf("%.2f", divide(7, 2));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Returning Characters
A function can return char to hand back a single character result -- useful for functions that classify input or compute something like a grade letter based on a numeric score.
Example: Returning Characters
#include <stdio.h>
char getGrade(int score) {
return (score >= 90) ? 'A' : 'B';
}
int main() {
printf("%c", getGrade(95));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using Returned Values in Expressions
A function's returned value can be used directly inside a larger expression -- like total = add(3, 4) * 2; -- without first storing it in an intermediate variable, since the call itself evaluates to that returned value.
Example: Using Returned Values in Expressions
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int total = add(3, 4) * 2;
printf("%d", total);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: