Variables, Expressions, and Assignment Statements 17
Constants for strings of characters are given in double quotes, as illustrated by the
following line taken from Display 1.1:
cout << "How many programming languages have you used? ";
Be sure to notice that string constants are placed inside double quotes, while constants
of type
char are placed inside single quotes. The two kinds of quotes mean different
things. In particular,
’A’ and "A" mean different things. ’A’ is a value of type char and
can be stored in a variable of type
char. "A" is a string of characters. The fact that the
string happens to contain only one character does not make
"A" a value of type char.
Also notice that for both strings and characters, the left and right quotes are the same.
Strings in double quotes, like
"Hello", are often called C-strings. In Chapter 9 we
will see that C++ has more than one kind of string, and this particular kind happens to
be called C-strings.
The type
bool has two constants, true and false. These two constants may be
assigned to a variable of type
bool or used anyplace else an expression of type bool is
allowed. They must be spelled with all lowercase letters.
■
ESCAPE SEQUENCES
A backslash, \ , preceding a character tells the compiler that the sequence following the
backslash
does not have the same meaning as the character appearing by itself. Such a
sequence is called an escape sequence. The sequence is typed in as two characters with
no space between the symbols. Several escape sequences are defined in C++.
If you want to put a backslash,
\, or a quote symbol, ", into a string constant, you
must escape the ability of the
" to terminate a string constant by using \", or the ability
of the
\ to escape, by using \\. The \\ tells the compiler you mean a real backslash, \,
not an escape sequence; the
\" tells it you mean a real quote, not the end of a string
constant.
A stray
\, say \z, in a string constant will have different effects on different compil-
ers. One compiler may simply give back a
z; another might produce an error. The
ANSI/ISO standard states that unspecified escape sequences have undefined behavior.
This means a compiler can do anything its author finds convenient. The consequence
is that code that uses undefined escape sequences is not portable. You should not use
any escape sequences other than those provided by the C++ standard. These C++ con-
trol characters are listed in Display 1.3.
■
NAMING CONSTANTS
Numbers in a computer program pose two problems. The first is that they carry no
mnemonic value. For example, when the number
10 is encountered in a program, it
gives no hint of its significance. If the program is a banking program, it might be the
number of branch offices or the number of teller windows at the main office. To
quotes
C-string
escape
sequence
01_CH01.fm Page 17 Wednesday, August 20, 2003 2:21 PM