Programming in C

(Barry) #1

120 Chapter 8 Working with Functions


The differences between printMessageand the function mainfrom Program 3.1 is in
the first and last line.The first line of a function definition tells the compiler (in order
from left to right) four things about the function:


  1. Who can call it (discussed in Chapter 15, “Working with Larger Programs”)

  2. The type of value it returns

  3. Its name

  4. The arguments it takes
    The first line of the printMessagefunction definition tells the compiler that the func-
    tion returns no value (the first use of the keyword void), its name is printMessage, and
    that it takes no arguments (the second use of the keyword void).You learn more details
    about the voidkeyword shortly.
    Obviously, choosing meaningful function names is just as important as choosing
    meaningful variable names—the choice of names greatly affects the program’s readability.
    Recall from discussions of Program 3.1 that mainis a specially recognized name in
    the C system that always indicates where the program is to begin execution.You must
    alwayshave a main.You can add a mainfunction to the preceding code to end up with a
    complete program, as shown in Program 8.1.


Program 8.1 Writing a Function in C
#include <stdio.h>

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

int main (void)
{
printMessage ();

return 0;
}

Program 8.1 Output
Programming is fun.

Program 8.1 consists of twofunctions:printMessageand main.Program execution
always begins with main. Inside that function, the statement
printMessage ();
Free download pdf