Returning values from functions
What you'll learn: How functions act like machines that take in raw materials and hand back a finished product using the return keyword.
The result of the work
In previous lessons, we used functions to perform actions, like printing text to the screen. However, the true power of a function is its ability to do a calculation and "hand back" the result to the part of the program that asked for it.
Think of a function like a vending machine. You provide an input (money and a selection), the machine performs an internal process, and it "returns" a snack to you. In C, we use the return statement to pass a value back to the caller.
Setting the return type
To make this work, we have to change the function's definition. Up until now, you may have used void, which tells C "this function returns nothing." If you want to return a whole number, you must change void to int.
The return keyword does two things:
- It immediately exits the function.
- It sends the specified value back to where the function was called.
Seeing it in action
Let’s look at a function that doubles a number. Notice how we capture the result in a variable back in main.
#include <stdio.h>
// This function takes an integer and returns an integer
int doubleNumber(int input) {
int result = input * 2;
return result; // The "finished product" is sent back here
}
int main() {
int myAmount = 25;
// We "catch" the returned value in a new variable
int total = doubleNumber(myAmount);
printf("Double %d is %d", myAmount, total);
return 0;
}
How the data flows
When doubleNumber(myAmount) is executed, the program jumps to the function, calculates 50, and then essentially "replaces" the function call in your code with that value. It is as if your code became int total = 50;.
You can return variables, math expressions, or even raw numbers. Just remember: once a function hits a return statement, it stops working and goes home. Anything written below a return inside that same function will never be executed.
Key takeaway
Use the return keyword to send a value out of a function, and ensure your function header matches the data type you are sending back.