A program’s declarations tell the C++ compiler the type of a particular integer variable. But what about constants? That is, suppose you represent a number with a constant in a program:
cout << "Year = " << 1492 << " ";
Does the program store 1492
as an int
, a long
, or some other integer type? The answer is that C++ stores integer constants as type int
unless there is a reason to do otherwise. Two such reasons are if you use a special suffix to indicate a particular type or if a value is too large to be an int
.
First, look at the suffixes. These are letters placed at the end of a numeric constant to indicate the type. An l
or L
suffix on an integer means the integer is a type long
constant, a u
or U
suffix indicates an unsigned int
constant, and ul
(in any combination of orders and uppercase and lowercase) indicates a type unsigned long
constant. (Because a lowercase l
can look much like the digit 1
, you should use the uppercase L
for suffixes.) For example, on a system using a 16-bit int
and a 32-bit long
, the number 22022
is stored in 16 bits as an int
, and the number 22022L
is stored in 32 bits as a long
. Similarly, 22022LU
and 22022UL
are unsigned long
. C++11 provides the ll
and LL
suffixes for type long long
, and ull
, Ull
, uLL
, and ULL
for unsigned long long
.
Next, look at size. C++ has slightly different rules for decimal integers than it has for hexadecimal and octal integers. (Here decimal means base 10, just as hexadecimal means base 16; the term decimal does not necessarily imply a decimal point.) A decimal integer without a suffix is represented by the smallest of the following types that can hold it: int
, long
, or long long
. On a computer system using a 16-bit int
and a 32-bit long
, 20000
is represented as type int
, 40000
is represented as long
, and 3000000000
is represented as long long
. A hexadecimal or octal integer without a suffix is represented by the smallest of the following types that can hold it: int
, unsigned int
, long
, unsigned long
, long long,
or unsigned long long
. The same computer system that represents 40000
as long
represents the hexadecimal equivalent 0x9C40 as an unsigned int
. That’s because hexadecimal is frequently used to express memory addresses, which intrinsically are unsigned. So unsigned int
is more appropriate than long
for a 16-bit address.
18.218.78.102