Returning Values from Functions
In addition to passing data to functions, you can have functions return data. They can return a single data item—an integer, for example—or an array or an object.
To indicate that a function returns a value, you specify the type of that data value first in a function definition or declaration. For example, you can alter the adder() function from the previous task to return an integer value holding the sum of the two values passed to it, like this:
int adder(int x, int y)
To actually return the sum of the two values passed to the adder() function, you use a return statement:
int adder(int x, int y) { return x + y; }
That’s how it works: to return a value from a function, you place the value you want to return right after the keyword return.
Now when you call the adder() function and pass data to that function, the call itself will be replaced by the function’s return value. So to add 5 and 10 and display the results, you can use this code:
int value1 = 5, value2 = 10; printf("%i + %i = %i", value1, value2, adder(value1, value2));
Listing 4.7. Starting functionreturn.m.
#include <stdio.h> int adder(int x, int y) { return x + y; } . . .
Listing 4.8. The functionreturn.m program.
#include <stdio.h> int adder(int x, int y) { return x + y; } int main() { int value1 = 5, value2 = 10; printf("%i + %i = %i", value1, value2, adder(value1, value2)); return 0; }
To return values from functions:
- Create a new program named functionreturn.m.
- In functionreturn.m, enter the code shown in Listing 4.7.
This code creates the adder() function and sets it up to return the sum of the two integers passed to it.
- Add the code to call the adder() function and pass two integers to it (Listing 4.8).
- Save functionreturn.m.
- Run the functionreturn.m program.
You should see the following:
5 + 10 = 15