2.1.3 Literals
A value, such as 42, is known as a literal because its value self-evident. Every literal has a type. The form and value of a literal determine its type.
Integer and Floating-Point Literals
We can write an integer literal using decimal, octal, or hexadecimal notation. Integer literals that begin with 0 (zero) are interpreted as octal. Those that begin with either 0x or 0X are interpreted as hexadecimal. For example, we can write the value 20 in any of the following three ways:
- 20 024 0x14
The type of an integer literal depends on its value and notation. By default, decimal literals are signed whereas octal and hexadecimal literals can be either signed or unsigned types. A decimal literal has the smallest type of int, long, or long long (i.e., the first type in this list) in which the literal’s value fits. Octal and hexadecimal literals have the smallest type of int, unsigned int, long, unsigned long, long long, or unsigned long long in which the literal’s value fits. It is an error to use a literal that is too large to fit in the largest related type. There are no literals of type short. We’ll see in Table 2.2 (p. 40) that we can override these defaults by using a suffix.
Although integer literals may be stored in signed types, technically speaking, the value of a decimal literal is never a negative number. If we write what appears to be a negative decimal literal, for example, -42, the minus sign is not part of the literal. The minus sign is an operator that negates the value of its (literal) operand.
Floating-point literals include either a decimal point or an exponent specified using scientific notation. Using scientific notation, the exponent is indicated by either E or e:
3.14159 3.14159E0 0. 0e0 .001
By default, floating-point literals have type double. We can override the default
using a suffix from Table 2.2 (overleaf).
Character and Character String Literals
A character enclosed within single quotes is a literal of type char. Zero or more characters enclosed in double quotation marks is a string literal:
- ’a’
- "Hello World!"
The type of a string literal is array of constant chars, a type we’ll discuss in § 3.5.4 (p. 122). The compiler appends a null character (’\0’) to every string literal. Thus, the actual size of a string literal is one more than its apparent size. For example, the literal ’A’ represents the single character A, whereas the string literal "A" represents an array of two characters, the letter A and the null character.
Two string literals that appear adjacent to one another and that are separated only by spaces, tabs, or newlines are concatenated into a single literal. We use this form of literal when we need to write a literal that would otherwise be too large to fit comfortably on a single line:
-
- std::cout << "a really, really long string literal "
- "that spans two lines" << std::endl;