I am trying this code on GNU's C++ compiler and am unable to understand its behaviour:
#include <stdio.h>; int main() { int num1 = 1000000000; long num2 = 1000000000; long long num3; //num3 = 100000000000; long long num4 = ~0; printf("%u %u %u", sizeof(num1), sizeof(num2), sizeof(num3)); printf("%d %ld %lld %llu", num1, num2, num3, num4); return 0; }
When I uncomment the commented line, the code doesn't compile and is giving an error:
error: integer constant is too large for long type
But, if the code is compiled as it is and is executed, it produces values much larger than 10000000000.
Why?
According to C99 standard, long long is an integer type which is at least 64-bit wide. There are two integer 64-bit types specified: long long int and unsigned long long int. So, yes, this is the biggest integer type specified by C language standard (C99 version).
long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise.
Executive summary: it's 64 bits, or larger. unsigned long long is the same as unsigned long long int . Its size is platform-dependent, but guaranteed by the C standard (ISO C99) to be at least 64 bits.
The letters 100000000000 make up a literal integer constant, but the value is too large for the type int
. You need to use a suffix to change the type of the literal, i.e.
long long num3 = 100000000000LL;
The suffix LL
makes the literal into type long long
. C is not "smart" enough to conclude this from the type on the left, the type is a property of the literal itself, not the context in which it is being used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With