Sams Teach Yourself C in 21 Days

(singke) #1
The Components of a C Program 31

2


25: /* Function returns the product of the two values provided */
26: int product(int x, int y)
27: {
28: return (x * y);
29: }

Enter a number between 1 and 100: 35
Enter another number between 1 and 100: 23
35 times 23 = 805

The Program’s Components ................................................................................

The following sections describe the various components of the preceding sample pro-
gram. Line numbers are included so that you can easily identify the program parts being
discussed.

Themain()Function (Lines 8 Through 23) ....................................................

The only component that is required in every executable C program is the main()func-
tion. In its simplest form, the main()function consists of the name mainfollowed by a
pair of parentheses containing the word void((void)) and a pair of braces ({}). You can
leave the word voidout and the program will still work with most compilers. The ANSI
standard states that you should include the word voidso that you know there is nothing
being sent to the mainfunction.
Within the braces are statements that make up the main body of the program. Under nor-
mal circumstances, program execution starts at the first statement in main()and termi-
nates at the last statement in main(). Per the ANSI standard, the only statement that you
need to include is this example is the returnstatement in line 22.

The#includeDirective (Line 2) ....................................................................

The#includedirective instructs the C compiler to add the contents of an include
file into your program during compilation. An include fileis a separate disk file
that contains information that can be used by your program or the compiler. Several of
these files (sometimes called header files) are supplied with your compiler. You rarely
need to modify the information in these files; that’s why they’re kept separate from your
source code. Include files should all have an .h extension (for example, stdio.h).
You use the #includedirective to instruct the compiler to add a specific include file to
your program during compilation. In Listing 2.1, the #includedirective is interpreted to

LISTING2.1 continued

INPUT/
OUTPUT

NEWTERM

05 448201x-CH02 8/13/02 11:14 AM Page 31

Free download pdf