Programming in C

(Barry) #1
Defining a Function 121

appears.This statement indicates that the function printMessageis to be executed.The
open and close parentheses are used to tell the compiler that printMessageis a function
and that no arguments or values are to be passed to this function (which is consistent
with the way the function is defined in the program).When a function call is executed,
program execution is transferred directly to the indicated function. Inside the
printMessagefunction, the printfstatement is executed to display the message
“Programming is fun.” at the terminal. After the message has been displayed, the
printMessageroutine is finished (as signaled by the closing brace) and the program
returnsto the mainroutine, where program execution continues at the point where the
function call was executed. Note that it is acceptable to insert a returnstatement at the
end of printMessagelike this:


return;


Because printMessagedoes not return a value, no value is specified for the return.This
statement is optional because reaching the end of a function without executing a return
has the effect of exiting the function anyway without returning a value. In other words,
either with or without the returnstatement, the behavior on exit from printMessage
is identical.
As mentioned previously, the idea of calling a function is not new.The printfand
scanfroutines are both program functions.The main distinction here is that these rou-
tines did not have to be written by you because they are a part of the standard C library.
When you use the printffunction to display a message or program results, execution is
transferred to the printffunction, which performs the required tasks and then returns
back to the program. In each case, execution is returned to the program statement that
immediately follows the call to the function.
Now try to predict the output from Program 8.2.


Program 8.2 Calling Functions


#include <stdio.h>


void printMessage (void)
{
printf ("Programming is fun.\n");
}


int main (void)
{
printMessage ();
printMessage ();


return 0;
}

Free download pdf