C++ literal integer type
Yes, literal numbers have types. The type of an unsuffixed decimal integer literal is the first of int
, long
, long long
in which the integer can be represented. The type of binary, hex and octal literals is selected similarly but with unsigned types in the list as well.
You can force the use of unsigned types by using a U
suffix. If you use a single L
in the suffix then the type will be at least long
but it might be long long
if it cannot be represented as a long
. If you use LL
, then the type must be long long
(unless the implementation has extended types wider than long long
).
The consequence is that if int
is a 32-bit type and long
is 64 bits, then 2147483647
has type int
while 2147483648
has type long
. That means that 2147483647+1
will overflow (which is undefined behaviour), while 2147483648+1
is simply 2147483649L
.
This is defined by §2.3.12 ([lex.icon]
) paragraph 2 of the C++ standard, and the above description is a summary of Table 7 from that section.
It's important to remember that the type of the destination of the assignment does not influence in any way the value of the expression on the right-hand side of the assignment. If you want to force a computation to have a long long
result you need to force some argument of the computation to be long long
; just assigning to a long long
variable isn't enough:
long long a = 2147483647 + 1LL;
std::cout << a << '\n';
produces
2147483648
(live on coliru)