Passing Arguments to a Function

If a function requires arguments, you list them in the parentheses of the function call. In the BEEPER1.C program below, we revise the beep function from BEEPER.C to take one argument.

/* BEEPER1.C: Demonstrate passing arguments. */

#include <stdio.h>

void beep( int num_beep );

main()

{

printf( "Time to beep\n" );

beep( 5 );

printf( "All done\n" );

}

void beep( int num_beep )

{

while( num_beep > 0 )

{

printf( "Beep!\n" );

num_beep = num_beep - 1;

}

}

The function definition states what kind of arguments the function expects. In the
beep function definition, the header,

void beep( int num_beep )

states that beep expects one int (integer) argument named num_beep
(number of beeps).

The statement that calls beep,

beep( 5 );

gives the value 5 in parentheses, passing that value as an argument. Figure 2.4 shows argument passing in BEEPER1.C.

Summary: Function arguments are assigned to local variables inside the function.

When beep receives the value 5, the function automatically assigns the value to num_beep, which the function can then treat as a local variable. In this case, the function uses num_beep as a loop counter to repeat the statement

printf( "Beep!\n" );

num_beep times. (The C while loop is very similar to WHILE loops in QuickBasic or QuickPascal. You don't need to know the details of loops for now; they're explained in Chapter 3, “Flow Control.”)

If a function expects more than one argument, you separate the arguments with commas. For instance, the statement

printf( "%d times %d equals %d\n", 2, 16, 2 * 16 );

passes four arguments to the printf function. The first argument is the string

"%d times %d equals %d\n"

The second and third arguments are constants (2 and 16). The fourth argument is an expression (2 * 16) that evaluates to a constant.