- A Short C Program
- The Program's Components
- A Review of the Parts of a Program
- Summary
- Q&A
- Workshop
The Program’s Components
The following sections describe the various components of the preceding sample program. Line numbers are included so that you can easily identify the program parts discussed.
The main() Function (Lines 9 Through 23)
The only component required in every executable C program is the main() function. In its simplest form, the main() function consists of the name main followed by a pair of parentheses containing the word void ((void)) and a pair of braces ({}). You can leave the word void out and the program still works with most compilers. The ANSI Standard states that you should include the word void so that you know there is nothing sent to the main function.
Within the braces are statements that make up the main body of the program. Under normal circumstances, program execution starts at the first statement in main() and terminates at the last statement in main(). Per the ANSI Standard, the only statement that you need to include in this example is the return statement on line 22.
The #include and #define Directives (Lines 2 and 3)
The #include directive instructs the C compiler to add the contents of an include file into your program during compilation. An include file is 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 #include directive to instruct the compiler to add a specific include file to your program during compilation. In Listing 2.1, the #include directive is interpreted to mean “Add the contents of the file stdio.h.” You will almost always include one or more include files in your C programs. Lesson 22, “Advanced Compiler Use” presents more information about include files.
The #define directive instructs the C compiler to replace a specific term with its assigned value throughout your program. By setting a variable at the top of your program and then using the term throughout the code, you can more easily change a term if needed by changing the single #define line as opposed to every place throughout the code. For example, if you wrote a payroll program that used a specific deduction for health insurance and the insurance rate changed, tweaking a variable created with #define named HEALTH_INSURANCE at the top of your program (or in a header file) would be so much easier than searching through lines and lines of code looking for every instance that had the information. Lesson 3, “Storing Information: Variables and Constants” covers the #define directive.
The Variable Definition (Line 5)
A variable is a name assigned to a location in memory used to store information. Your program uses variables to store various kinds of information during program execution. In C, a variable must be defined before it can be used. A variable definition informs the compiler of the variable’s name and the type of information the variable is to hold. In the sample program, the definition on line 4, int year1, year2;, defines two variables—named year1 and year2—that each hold an integer value. Lesson 3 presents more information about variables and variable definitions.
The Function Prototype (Line 7)
A function prototype provides the C compiler with the name and arguments of the functions contained in the program. It appears before the function is used. A function prototype is distinct from a function definition, which contains the actual statements that make up the function. (Function definitions are discussed in more detail in “The Function Definition” section.)
Program Statements (Lines 12, 13, 14, 17, 19, 20, 22, and 28)
The real work of a C program is done by its statements. C statements display information onscreen, read keyboard input, perform mathematical operations, call functions, read disk files, and all the other operations that a program needs to perform. Most of this book is devoted to teaching you the various C statements. For now, remember that in your source code, C statements are generally written one per line and always end with a semicolon. The statements in bigyear.c are explained briefly in the following sections.
The printf() Statement
The printf() statement (lines 12, 13, 19, and 20) is a library function that displays information onscreen. The printf() statement can display a simple text message (as in lines 12 and 13) or a message mixed with the value of one or more program variables (as in lines 19-20).
The scanf() Statement
The scanf() statement (line 14) is another library function. It reads data from the keyboard and assigns that data to one or more program variables.
The program statement on line 17 calls the function named calcYear(). In other words, it executes the program statements contained in the function calcYear(). It also sends the argument year1 to the function. After the statements in calcYear() are completed, calcYear() returns a value to the program. This value is stored in the variable named year2.
The return Statement
Lines 22 and 28 contain return statements. The return statement on line 28 is part of the function calcYear(). It calculates the year a person would be a specific age by adding the #define constant TARGET_AGE to the variable year1 and returns the result to the program that called calcYear(). The return statement on line 22 returns a value of 0 to the operating system just before the program ends.
The Function Definition (Lines 26 Through 29)
When defining functions before presenting the program bigyear.c, two types of functions—library functions and user-defined functions—were mentioned. The printf() and scanf() statements are examples of the first category, and the function named calcYear(), on lines 26 through 29, is a user-defined function. As the name implies, user-defined functions are written by the programmer during program development. This function adds the value of a created constant to a year and returns the answer (a different year) to the program that called it. In Lesson 5, “Packaging Code in Functions,” you learn that the proper use of functions is an important part of good C programming practice.
Note that in a real C program, you probably wouldn’t use a function for a task as simple as adding two numbers. It has been done here for demonstration purposes only.
Program Comments (Lines 1, 11, 16, and 25)
Any part of your program that starts with /* and ends with */ or any single line that begins with // is called a comment. The compiler ignores all comments, so they have absolutely no effect on how a program works. You can put anything you want into a comment, and it won’t modify the way your program operates. The first type of comment can span part of a line, an entire line, or multiple lines. Here are three examples:
/* A single-line comment */ int a,b,c; /* A partial-line comment */ /* a comment spanning multiple lines */
You should not use nested comments. A nested comment is a comment that has been put into another comment. Most compilers will not accept the following:
/* /* Nested comment */ */
Some compilers do allow nested comments. Although this feature might be tempting to use, you should avoid doing so. Because one of the benefits of C is portability, using a feature such as nested comments might limit the portability of your code. Nested comments also might lead to hard-to-find problems.
The second style of comment, the ones beginning with two consecutive forward slashes (//), are only for single-line comments. The two forward slashes tell the compiler to ignore everything that follows to the end of the line.
// This entire line is a comment int x; // Comment starts with slashes
Many beginning programmers view program comments as unnecessary and a waste of time. This is a mistake! The operation of your program might be quite clear when you write the code; however, as your programs become larger and more complex, or when you need to modify a program you wrote 6 months ago, comments are invaluable. Now is the time to develop the habit of using comments liberally to document all your programming structures and operations. You can use either style of comments you prefer. Both are used throughout the programs in the book.
Using Braces (Lines 10, 23, 27, and 29)
You use braces {} to enclose the program lines that make up every C function—including the main() function. A group of one or more statements enclosed within braces is called a block. As you see in later lessons, C has many uses for blocks.
Running the Program
Take the time to enter, compile, and run bigyear.c. It provides additional practice in using your editor and compiler. Recall these steps from Lesson 1, “Getting Started with C”:
- Make your programming directory current.
- Start your editor.
- Enter the source code for bigyear.c exactly as shown in Listing 2.1, but be sure to omit the line numbers and colons.
- Save the program file.
- Compile and link the program by entering the appropriate command(s) for your compiler. If no error messages display, you can run the program by clicking the appropriate button in your C environment.
- If any error messages display, return to step 2 and correct the errors.
A Note on Accuracy
A computer is fast and accurate, but it also is completely literal. It doesn’t know enough to correct your simplest mistake; it takes everything you enter exactly as you entered it, not as you meant it!
This goes for your C source code as well. A simple typographical error in your program can cause the C compiler to choke, gag, and collapse. Fortunately, although the compiler isn’t smart enough to correct your errors (and you’ll make errors—everyone does!), it is smart enough to recognize them as errors and report them to you. (You saw in Lesson 1 how the compiler reports error messages and how you interpret them.)