return expr; ends the function and gives expr back to the caller, converted to the return type. A function can have several return statements, which is handy for early exits that avoid deep nesting. Functions return one value; use a struct or pointers for more.
Remember
int f(int n) {
if (n < 0) return -1; /* early return */
return n * 2;
}
Reference
Cheat Sheet
Keep these facts handy while you work with Return Values in C.
Topic
Detail
void function
return; with no value
Single value
Return type decides conversion
Several results
Return a struct or use pointer parameters
Local addresses
Never return a pointer to a local variable
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Function Prototypes.
Example 1 — Early returns in a prime test
Each return exits immediately.
C
#include <stdio.h>
int is_prime(int n) {
if (n < 2) return 0;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return 0;
}
return 1;
}
int main(void) {
int tests[] = {1, 7, 9, 13};
for (int i = 0; i < 4; i++) {
printf("%d -> %s\n", tests[i], is_prime(tests[i]) ? "prime" : "not prime");
}
return 0;
}
Output
1 -> not prime
7 -> prime
9 -> not prime
13 -> prime
How It Works
Numbers below 2 return 0 right away.
The loop returns 0 at the first divisor found.
If no divisor exists the function reaches return 1;.
Edge Cases & Pitfalls
Check these before relying on Return Values in real programs.
local
Returning a local address
int *f(void){ int x=5; return &x; } returns a dangling pointer. Use static, a parameter, or malloc.
ignored
Using main's return wrongly
main should return 0 for success and non-zero for errors.
Remember
Key Takeaways
Exit:return ends the function.
Many: early returns simplify logic.
Safe: never return a local address.
One line: return expr; ends the function and gives expr back to the caller, converted to the return type.
Frequently Asked Questions
Not directly. Return a pointer to a static or heap array, wrap the array in a struct, or fill a caller-supplied buffer.
It reports success to the operating system. Non-zero values (or EXIT_FAILURE) signal an error.
Continue with "C Function Prototypes" next. Declare a function signature before its first use. The C Functions hub lists every topic in order.