Explaining the Sampl e Program
Now that you have an overview of a C++ program, its struc- ture, and its comments, the rest of this chapter walks you through the entire sample program. Do not expect to become a C++ expert just by completing this section—that is what the rest of the book is for! For now, just sit back and follow this step-by-step description of the program code.
EXAMPLE
As described earlier, this sample program contains several comments. The first three lines of the program are comments:
/ / 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.
This comment lists the filename and explains the purpose of the program. This is not the only comment in the program; others appear throughout the code.
The next line beginning with #i ncl ude is called a preprocessor directive and is shown here:
#i ncl ude <i ost r eam. h>
This strange looking statement is not actually a C++ command, but is a directive that instructs the C++ compiler to load a file from disk into the middle of the current program. The only purpose for this discussion is to ensure that the output generated with cout works properly. Chapter 6, “Preprocessor Directives,” more fully explains this directive.
The next two lines (following the blank separating line) are shown here:
mai n( )
{
This begins the mai n() function. Basically, the mai n() function’s opening and closing braces enclose the body of this program and mai n() ’s instructions that execute. C++ programs often contain more than one function, but they always contain a function called mai n() . The mai n() function does not have to be the first one, but it usually is. The opening brace begins the first and only block of this program. When a programmer compiles and runs this program, the computer looks for mai n() and starts executing whatever instruction follows mai n() ’s opening brace. Here are the three lines that follow:
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;
Chapter 3 ♦Your First C++ Program
These three lines declare variables. A variable declaration describes variables used in a block of code. Variable declarations describe the program’s data storage.
A C++ program processes data into meaningful results. All C++ programs include the following:
-
Commands
-
Data
Data comprises variables and literals (sometimes called con- stants). As the name implies, a variable is data that can change (become variable) as the program runs. A literal remains the same. In life, a variable might be your salary. It increases over time (if you are lucky). A literal would be your first name or social security number, because each remains with you throughout life and does not (naturally) change.
Chapter 4, “Variables and Literals,” fully explains these con- cepts. However, to give you an overview of the sample program’s elements, the following discussion explains variables and literals in this program.
C++ enables you to use several kinds of literals. For now, you simply have to understand that a C++ literal is any number, charac- ter, word, or phrase. The following are all valid C++ literals:
5. 6
- 45 ‘ Q’
“ Mary” 18. 67643
0. 0
As you can see, some literals are numeric and some are
character-based. The single and double quotation marks around two of the literals, however, are not part of the actual literals. A single-character literal requires single quotation marks around it; a string of characters, such as “ Mar y” , requires double quotation marks.
EXAMPLE
Look for the literals in the sample program. You find these:
4
7
‘ A’
9. 087
4. 5
A variable is like a box inside your computer that holds
something. That “something” might be a number or a character. You can have as many variables as needed to hold changing data. After you define a variable, it keeps its value until you change it or define it again.
Variables have names so you can tell them apart. You use the assignment operator, the equal sign (=), to assign values to variables. The following statement,
sal es=25000;
puts the literal value 25000 into the variable named sal es . In the sample program, you find the following variables:
i j c
x
The three lines of code that follow the opening brace of the
sample program declare these variables. This variable declaration informs the rest of the program that two integer variables named i and j as well as a character variable called c and a floating-point variable called x appear throughout the program. The terms integer and floating-point basically refer to two different types of numbers: Integers are whole numbers, and floating-point numbers contain decimal points.
The next few statements of the sample program assign values to these variables.
Chapter 3 ♦Your First C++ Program
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.
The first line puts 4 in the integer variable, i . The second line adds 7 to the variable i ’s value to get 11, which then is assigned to (or put into) the variable called j . The plus sign (+) in C++ works just like it does in mathematics. The other primary math operators are shown in Table 3.1.
Table 3.1. The primary math operators.
Operator |
Meaning |
Example |
---|---|---|
+ |
Addition |
4 + 5 |
– |
Subtraction |
7 – 2 |
* |
Multiplication |
12 * 6 |
/ |
Division |
48 / 12 |
The character literal A is assigned to the c variable. The number
- 087
is assigned to the variable called x, then x is immediately overwritten with a new value: itself (9. 087 ) multiplied by 4.5. This helps illustrate why computer designers use an asterisk (* ) for multiplication and not a lowercase x as people generally do to show multiplication; the computer would confuse the variable x with the multiplication symbol, x, if both were allowed.
EXAMPLE
Put ar et ur n
The next line (after the comment) includes the following special—and, at first, confusing—statement:
cout << i << “ , “ << j << “ , “ << c << “ , “ << x << “ \ n” ;
When the program reaches this line, it prints the contents of the four variables on-screen. The important part of this line is that the four values for i , j , c, and x print on-screen.
The output from this line is
4, 11, A, 40. 891499
Because this is the only cout in the program, this is the only output the sample program produces. You might think the program is rather long for such a small output. After you learn more about C++, you should be able to write more useful programs.
The cout is not a C++ command. You might recall from Chapter 2, “What Is a Program?,” that C++ has no built-in input/ output commands. The cout is an operator, described to the compiler in the #i ncl ude file called iostream.h, and it sends output to the screen.
C++ also supports the pr i ntf () function for formatted output. You have seen one function already, mai n() , which is one for which you write the code. The C++ programming designers have already written the code for the pr i nt f function. At this point, you can think of pr i ntf as a command that outputs values to the screen, but it is actually a built-in function. Chapter 7, “Simple Input/ Output” describes the pr i ntf function in more detail.
The last two lines in the program are shown here:
statement at the end
of each function.
r et ur n 0; / / ALWAYS end pr ogr ams and f unct i ons wi t h r et ur n.
}
Chapter 3 ♦Your First C++ Program
The r et ur n command simply tells C++ that this function is finished. C++ returns control to whatever was controlling the pro- gram before it started running. In this case, because there was only one function, control is returned either to DOS or to the C++ editing environment. C++ requires a return value. Most C++ programmers return a 0 (as this program does) to the operating system. Unless you use operating-system return variables, you have little use for a return value. Until you have to be more specific, always return a 0 from mai n() .
Actually, many r et ur n statements are optional. C++ would know when it reached the end of the program without this state- ment. It is a good programming practice, however, to put a r et ur n statement at the end of every function, including mai n() . Because some functions require a r et ur n statement (if you are returning values), it is better to get in the habit of using them, rather than run the risk of leaving one out when you really need it.
You will sometimes see parentheses around the r et ur n value, as in:
r et ur n ( 0) ; / / ALWAYS end pr ogr ams and f unct i ons wi t h r et ur n.
The parentheses are unnecessary and sometimes lead begin- ning C++ students into thinking that r et ur n is a built-in function. However, the parentheses are recommended when you want to return an expression. You read more about returning values in Chapter 19, “Function Return Values and Prototypes.”
The closing brace after the r et ur n does two things in this program. It signals the end of a block (begun earlier with the open- ing brace), which is the end of the mai n() function, and it signals the end of the program.