Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

long long in C/C++

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?

like image 207
sud03r Avatar asked Sep 22 '09 09:09

sud03r


People also ask

What is a long long in C?

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).

Is long long supported in C?

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.

How many bits is a long long in C?

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.


1 Answers

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.

like image 50
unwind Avatar answered Sep 28 '22 09:09

unwind