Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 4. Creating Functions > Passing Arguments to Functions

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);
}

✓ Tip

  • You specify the type (int here) of every argument in the list just before its name.


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:

1.
Create a new program named functionargs.m.

2.
In functionargs.m, enter the code shown in Listing 4.5.

This code creates the adder() function.

3.
Enter the code to specify the main() function and the call to the adder() function to add 5 plus 10 (Listing 4.6).

4.
Save functionargs.m.

5.
Run the functionargs.m program.

You should see the following:

5 + 10 = 15

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint