Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ literal integer type

Do literal expressions have types too ?

long long int a = 2147483647+1 ;
long long int b = 2147483648+1 ; 
std::cout << a << ',' << b ; // -2147483648,2147483649
like image 618
Abhinav Vishak Avatar asked Mar 19 '17 21:03

Abhinav Vishak


People also ask

What are the 6 types of literals?

Primitive data types include int, byte, short, float, boolean, double, and char, whereas non-primitive data types include arrays, string, and classes. The primitive literals in java int, byte, short, float, boolean, double, and char represent certain signed integer values.

What is a literal value in C?

Literals are the constant values assigned to the constant variables. We can say that the literals represent the fixed values that cannot be modified. It also contains memory but does not have references as variables. For example, const int =10; is a constant integer expression in which 10 is an integer literal.

Where are integer literals stored in C?

The constant 1 and the expression -1 are both of type int . The value is stored in the int object i ; no conversion is necessary.


1 Answers

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)

like image 147
rici Avatar answered Sep 22 '22 21:09

rici