Constant values
In C++, a const must always have
an initialization value (in C, this is not true). Constant values for built-in
types are expressed as decimal,
octal, hexadecimal, or
floating-point numbers (sadly, binary numbers were not
considered important), or as characters.
In the absence of any other clues, the
compiler assumes a constant value is a decimal number. The numbers 47, 0, and
1101 are all treated as decimal numbers.
A constant value with a leading 0 is
treated as an octal number (base 8). Base 8 numbers can contain only digits 0-7;
the compiler flags other digits as an error. A legitimate octal number is 017
(15 in base 10).
A constant value with a leading 0x is
treated as a hexadecimal number (base 16). Base 16 numbers contain the digits
0-9 and a-f or A-F. A legitimate hexadecimal number is 0x1fe (510 in base
10).
Floating point numbers can contain
decimal points and exponential powers (represented by e,
which means “10 to the power of”). Both the decimal point and the
e are optional. If you assign a constant to a floating-point variable,
the compiler will take the constant value and convert it to a floating-point
number (this process is one form of what’s called implicit type
conversion). However, it is a
good idea to use either a decimal point or an e to remind the reader that
you are using a floating-point number; some older compilers also need the
hint.
Legitimate floating-point constant values
are: 1e4, 1.0001, 47.0, 0.0, and -1.159e-77. You can add suffixes to force the
type of floating-point number: f or F forces a float,
L or l forces a long double; otherwise the number
will be a
double.
Character
constants are characters surrounded by single quotes, as:
‘A’, ‘0’, ‘ ‘. Notice there is
a big difference between the character ‘0’ (ASCII 96) and the
value 0. Special characters are represented with the “backslash
escape”: ‘\n’ (newline), ‘\t’ (tab),
‘\\’ (backslash), ‘\r’ (carriage return),
‘\"’ (double quotes), ‘\'’ (single quote),
etc. You can also express char constants in octal: ‘\17’ or
hexadecimal:
‘\xff’.