Passing Arguments to Functions
You can pass data to functions so they can work on that data. For example, you can create a function named adder() that you want to add two integers and display the results.
To indicate which arguments a function takes, you include an argument list in the parentheses following the function name when you define the function. For example, the adder()function takes two arguments: the two integers to add, which we’ll name x and y:
void adder(int x, int y)
Now in the body of the function, you can refer to the first argument as x and the second argument as y.
When you create a function prototype, on the other hand (when you call the function before defining it in your code), you omit the names of the arguments, instead including just the type:
void adder(int, int);
Now you can write the body of the adder() function to add the two integers, which you can refer to by name, x and y:
void adder(int x, int y) { printf("%i + %i = %i", x, y, x + y); }
Listing 4.5. Starting functionargs.m.
#include <stdio.h> void adder(int x, int y) { printf("%i + %i = %i", x, y, x + y); } . . .
Listing 4.6. The functionargs.m program.
#include <stdio.h> void adder(int x, int y) { printf("%i + %i = %i", x, y, x + y); } int main() { int value1 = 5, value2 = 10; adder(value1, value2); return 0; }
To pass arguments to a function:
- Create a new program named functionargs.m.
- In functionargs.m, enter the code shown in Listing 4.5.
This code creates the adder() function.
- Enter the code to specify the main() function and the call to the adder() function to add 5 plus 10 (Listing 4.6).
- Save functionargs.m.
- Run the functionargs.m program.
You should see the following:
5 + 10 = 15