Looking at a C++ Progra m
Figure 3.1 shows the outline of a typical small C++ program. No C++ commands are shown in the figure. Although there is much more to a program than this outline implies, this is the general format of the beginning examples in this book.
Preprocessor directives go here
Function name
Block
Figure 3.1. A skeleton outline of a simple C++ program.
To acquaint yourself with C++ programs as fast as possible, you should begin to look at a program in its entirety. The following is a listing of a simple example C++ program. It doesn’t do much, but it enables you to see the general format of C++ programming. The next few sections cover elements from this and other programs. You might not understand everything in this program, even after finish- ing the chapter, but it is a good place to start.
/ / Fil ename: C3FI RST. CPP
/ / I ni t i al C++ pr ogr am t hat demonst r at es t he C++ comment s
/ / and shows a f ew var i abl es and t hei r decl ar at i ons.
EXAMPLE
#i ncl ude <i ost r eam. h> mai n( )
{
i nt i , j ; / / These t hr ee li nes decl ar e f our var i abl es. char c;
f l oat x;
i = 4; / / i and j ar e bot h assi gned i nt eger li t er al s. j = i
- 7;
c = ‘ A’ ; / / All char act er li t er al s ar e
/ / encl osed i n si ngl e quot at i ons.
x = 9. 087; / / x r equi r es a f l oat i ng- poi nt val ue because i t
/ / was decl ar ed as a f l oat i ng- poi nt var i abl e. x = x * 4. 5; / / Change what was i n x wi t h a f ormul a.
/ / Sends t he val ues of t he var i abl es t o t he scr een.
cout << i << “ , “ << j << “ , “ << c << “ , “ << x << “ \ n” ;
r et ur n 0; / / ALWAYS end pr ogr ams and f unct i ons wi t h r et ur n.
/ / The 0 r et ur ns t o t he oper at i ng syst em and
/ / usuall y i ndi cat es no err or s occurr ed.
}
For now, familiarize yourself with this overall program. See if
you can understand any part or all of it. If you are new to program- ming, you should know that the computer reads each line of the program, starting with the first line and working its way down, until it has completed all the instructions in the program. (Of course, you first have to compile and link the program, as described in Chap- ter 2, “What Is a Program?”.)
The output of this program is minimal: It simply displays four values on-screen after performing some assignments and calcula- tions of arbitrary values. Just concentrate on the general format at this point.
C++ is a free-form language.
The Format of a C++ Progra m
Unlike some other programming languages, such as COBOL, C++ is a free-form language, meaning that programming statements
Chapter 3 ♦Your First C++ Program
can start in any column of any line. You can insert blank lines in a program if you want. This sample program is called C3FIRST.CPP (you can find the name of each program in this book in the first line of each program listing). It contains several blank lines to help separate parts of the program. In a simple program such as this, the separation is not as critical as it might be in a longer, more complex program.
Generally, spaces in C++ programs are free-form as well. Your goal should not be to make your programs as compact as possible. Your goal should be to make your programs as readable as possi- ble. For example, the C3FIRST.CPP program shown in the previous section could be rewritten as follows:
/ / Fil ename: C3FI RST. CPP I ni t i al C++ pr ogr am t hat demonst r at es
/ / t he C++ comment s and shows a f ew var i abl es and t hei r
/ / decl ar at i ons.
#i ncl ude <i ost r eam. h>
mai n(){ i nt i , j ; / / These t hr ee li nes decl ar e f our var i abl es.
char c;f l oat x; i =4; / / i and j ar e bot h assi gned i nt eger li t er al s. j =i +7; c=’ A’ ; / / All char act er li t er al s ar e encl osed i n
// si ngl e quot at i ons.
x=9. 087;// x r equi r es a f l oat i ng- poi nt val ue because i t was
// decl ar ed as a f l oat i ng- poi nt var i abl e.
x=x* 4. 5;// Change what was i n x wi t h a f ormul a.
// Sends t he val ues of t he var i abl es t o t he scr een.
cout <<i <<“ , “ <<j <<“ , “ <<c<<“ , “ <<x<<“ \ n” ; r et ur n 0; / / ALWAYS
// end pr ogr ams and f unct i ons wi t h r et ur n. The 0 r et ur ns t o
//t he oper at i ng syst em and usuall y i ndi cat es no err or s occurr ed.
}
To your C++ compiler, the two programs are exactly the same, and they produce exactly the same result. However, to people who have to read the program, the first style is much more readable.
Readability Is the Ke y
As long as programs do their job and produce correct output, who cares how well they are written? Even in today’s world of fast computers and abundant memory and disk space, you should still
EXAMPLE
Use lowercase
care. Even if nobody else ever looks at your C++ program, you might have to change it at a later date. The more readable you make your program, the faster you can find what needs changing, and change it accordingly.
If you work as a programmer for a corporation, you can almost certainly expect to modify someone else’s source code, and others will probably modify yours. In programming departments, it is said that long-term employees write readable programs. Given this new global economy and all the changes that face business in the years ahead, companies are seeking programmers who write for the future. Programs that are straightforward, readable, abundant with white space (separating lines and spaces), and devoid of hard-to-read “tricks” that create messy programs are the most desirable.
Use ample white space so you can have separate lines and spaces throughout your programs. Notice the first few lines of C3FIRST.CPP start in the first column, but the body of the program is indented a few spaces. This helps programmers “zero in” on the important code. When you write programs that contain several sections (called blocks), your use of white space helps the reader’s eye follow and recognize the next indented block.
Uppercase Versus Lowercas e
Your uppercase and lowercase letters are much more signifi-
abundantly in C++!
cant in C++ than in most other programming languages. You can see that most of C3FIRST.CPP is in lowercase. The entire C++ language is in lowercase. For example, you must type the keywords i nt , char , and r et ur n in programs using lowercase characters. If you use uppercase letters, your C++ compiler would produce many errors and refuse to compile the program until you correct the errors. Appendix E, “Keyword and Function Reference,” shows a list of every command in the C++ programming language. You can see that none of the commands have uppercase letters.
Many C++ programmers reserve uppercase characters for some words and messages sent to the screen, printer, or disk file; they use lowercase letters for almost everything else. There is, however, one exception to this rule in Chapter 4, “Variables and Literals,” dealing with the const keyword.
Chapter 3 ♦Your First C++ Program
Braces an d mai n( )
All C++ programs require the following lines:
mai n( )
{
A C++ block is enclosed in two braces.
All executable C++ statements must end with a semi- colon (; ).
The statements that follow mai n() are executed first. The section of a C++ program that begins with mai n() , followed by an opening brace, { , is called the main function. A C++ program is actually a collection of functions (small sections of code). The function called mai n() is always required and always the first function executed.
In the sample program shown here, almost the entire program is mai n() because the matching closing brace that follows mai n() ’s opening brace is at the end of the program. Everything between two matching braces is called a block. You read more about blocks in Chapter 16, “Writing C++ Functions.” For now, you only have to realize that this sample program contains just one function, mai n() , and the entire function is a single block because there is only one pair of braces.
All executable C++ statements must have a semicolon (; ) after them so C++ is aware that the statement is ending. Because the computer ignores all comments, do not put semicolons after your comments. Notice that the lines containing mai n() and braces do not end with semicolons either, because these lines simply define the beginning and ending of the function and are not executed.
As you become better acquainted with C++, you learn when to include the semicolon and when to leave it off. Many beginning C++ programmers learn quickly when semicolons are required; your compiler certainly lets you know if you forget to include a semicolon where one is needed.
Figure 3.2 repeats the sample program shown in Figure 3.1. It contains additional markings to help acquaint you with these new terms as well as other items described in the remainder of this chapter.
EXAMPLE
Comments
Preprocessor directive
Begin block
Variable declarations
Body of program
End block
Figure 3.2. The parts of the sample program.
Comments in C+ +
In Chapter 2, “What Is a Program?,” you learned the difference between a program and its output. Most users of a program do not see the actual program; they see the output from the execution of the program’s instructions. Programmers, on the other hand, look at the program listings, add new routines, change old ones, and update for advancements in computer equipment.
Chapter 3 ♦Your First C++ Program
Comments tell peoplewhat the program is doing.
As explained earlier, the readability of a program is important so you and other programmers can look through it easily. Neverthe- less, no matter how clearly you write C++ programs, you can always enhance their readability by adding comments throughout.
Comments are messages that you insert in your C++ programs, explaining what is going on at that point in the program. For example, if you write a payroll program, you might put a comment before the check-printing routine that describes what is about to happen. You never put C++ language statements inside a comment, because a comment is a message for people—not computers. Your C++ compiler ignores all comments in every program.
Some programmers choose to comment several lines. Notice in the sample program, C3FIRST.CPP, that the first three lines are comment lines. The comments explain the filename and a little about the program.
Comments also can share lines with other C++ commands. You can see several comments sharing lines with commands in the C3FIRST.CPP program. They explain what the individual lines do. Use abundant comments, but remember who they’re for: people, not computers. Use comments to help explain your code, but do not overcomment. For example, even though you might not be familiar with C++, the following statement is easy: It prints “C++ By Ex- ample” on-screen.
cout << “ C++ By Exampl e” ; / / Pr i nt C++ By Exampl e on- scr een.
This comment is redundant and adds nothing to your under- standing of the line of code. It would be much better, in this case, to leave out the comment. If you find yourself almost repeating the C++ code, leave out that particular comment. Not every line of a C++ program should be commented. Comment only when code lines need explaining—in English—to the people looking at your program.
It does not matter if you use uppercase, lowercase, or a mixture of both in your comments because C++ ignores them. Most C++
EXAMPLE
programmers capitalize the first letter of sentences in comments, just as you would in everyday writing. Use whatever case seems appropriate for the letters in your message.
C++ can also use C-style comments. These are comments that begin with / * and end with * / . For instance, this line contains a comment in the C and C++ style:
net pay = gr osspay - t axes; / * Comput e t ake- home pay. * /
Examples
- Suppose
you want to write a C++ program that produces a fancy boxed title containing your name with flashing dots around it (like a marquee). The C++ code to do this might be difficult to understand. Before such code, you might want to insert the following comment so others can understand the code later:
/ / The f oll owi ng f ew li nes dr aw a f ancy box ar ound
/ / a name, t hen di spl ay f l ashi ng dot s ar ound t he
/ / name li ke a Holl ywood movi e mar quee.
Chapter 3 ♦Your First C++ Program
This would not tell C++ to do anything because a comment is not a command, but it would make the next few lines of code more understandable to you and others. The comment explains in English, for people reading the program, exactly what the program is getting ready to do.
- You
should also put the disk filename of the program in one of the first comments. For example, in the C3FIRST.CPP program shown earlier, the first line is the beginning of a comment:
/ / Fil ename: C3FI RST. CPP
The comment is the first of three lines, but this line tells you in which disk file the program is stored. Throughout this book, programs have comments that include a possible filename under which the program can be stored. They begin with Cx, where x is the chapter number in which they appear (for example, C6VARPR.CPP and C10LNIN.CPP).
This method helps you find these programs when they are discussed in another section of the book.