The return statement flow
What you'll learn: How the return keyword acts as a "teleportation" device that stops a function and sends a specific value back to the caller.
The Exit Door
Imagine a function as a separate room in a house. When your program enters that room, it starts following the instructions written on the walls. The return statement is the exit door. The moment the program hits a return, it stops whatever it is doing—even if there are more instructions below it—and immediately jumps back to the main hallway where it came from.
If a function is supposed to give you a result (like a calculation), it carries that result through the door with it.
One Way Out
Think of return as a "stop and deliver" command. Once a return is triggered, the function’s job is finished. You cannot have the computer perform more tasks within that specific function call after a return has executed. It’s like a waiter bringing your food; once they deliver the plate and walk back to the kitchen, they aren't standing at your table anymore.
#include <stdio.h>
int giveMeFive() {
printf("I am about to return 5...\n");
return 5;
// The line below will NEVER happen.
// The program has already left the room.
printf("You will never see this message.");
}
int main() {
int result;
// The program jumps to giveMeFive(), gets the 5,
// and brings it back to store in 'result'.
result = giveMeFive();
printf("The function gave us: %d", result);
return 0;
}
Handing Off the Baton
When you use return, you are essentially replacing the function call in your code with a raw value. In the example above, result = giveMeFive(); eventually becomes result = 5;.
The flow is circular: main calls the function, the function runs its logic, hits the return, and the flow "teleports" back to exactly where it left off in main, carrying the data like a baton in a relay race. If you forget to provide a return in a function that promises an integer, the program gets confused because it’s waiting at the door for a package that never arrives.
Key takeaway
The return statement immediately ends the current function's execution and hands a single value back to wherever the function was called.