Assigning Parameters

When you list a parameter in the function header, it becomes a local variable within the function. This process is easy to follow when it involves only one argument, as in the BEEPER1.C program above. The function call passes one value, which the function assigns to one variable. The variable can be treated like any other variable declared within the function.

Summary: There is a one-to-one correspondence between arguments and parameters.

If a function takes more than one argument, the values are passed in order. The first argument in the function call is assigned to the first variable, the second argument is assigned to the second variable, and so on.

The SHOWME.C program below demonstrates this process. Its showme function takes three arguments. The main function defines three integer variables and passes their values to showme, which prints the values that it receives. (You normally wouldn't write a function just to print one line, of course. We'll add more to SHOWME.C in a later revision.)

/* SHOWME.C: Demonstrate passing by value. */

#include <stdio.h>

void showme( int a, int b, int c );

main()

{

int x = 10, y = 20, z = 30;

showme( z, y, x );

}

void showme( int a, int b, int c )

{

printf( "a=%d b=%d c=%d", a, b, c );

}

Here's the output from SHOWME.C:

a=30 b=20 c=10

The function call in SHOWME.C passes the values of z, y, and x in the order listed:

showme( z, y, x );

These values are assigned, in the same order, to the parameters listed in the showme function header:

void showme( int a, int b, int c )

The position of the parameters, not their names, controls which arguments the parameters receive. The first argument (z) listed in the function call is assigned to the first parameter (a) in the function header, the second argument (y) to the second parameter (b), and so on. Figure 2.5 shows this process.