Calling a Function

You call (execute) a function by stating its name. In the simplest case—when a function doesn't receive or return any data—the function call consists of the function's name, followed by an empty pair of parentheses and a semicolon. The BEEPER.C program, shown below, demonstrates this kind of function call.

/* BEEPER.C: Demonstrate simple function. */

#include <stdio.h>

void beep( void );

main()

{

printf( "Time to beep\n" );

beep();

printf( "All done\n" );

}

void beep( void )

{

printf( "Beep!\n" );

}

When you run BEEPER.C, the program prints:

Time to beep

Beep!

All done

In the main function of BEEPER.C, the statement

beep();

calls the beep function. Since beep takes no arguments, the parentheses of the function call are empty.

The prototype and definition for the beep function use the void keyword twice, first to indicate that the function returns no value, and second to indicate that it receives no arguments. We'll return to these points later in this chapter.

A function call transfers control to that function. The statements within the function's braces execute in order until the function ends. Then execution resumes where it left off.

A function can end in one of two ways. The beep function above ends by “falling off” the closing brace of the function definition. A function can also end by executing a return statement, which we discuss later in the section “Returning Values from Functions.”

Figure 2.3 illustrates the flow of control in BEEPER.C.