Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't assign -2147483648 to variable of type long long

Tags:

c

I'm compiling the code below and for some reason I can't assign -2147483648 to the variable which is 8 bytes long and signed.

long long x = -2147483648;

When I step over this line, the value of x is 2147483648 and the 'Watch' window in MS Visual Studio shows that the type of x is __int64. A sizeof(x) also returns 8.

According to limit.h the limits for a signed long long are:

#define LLONG_MAX     9223372036854775807i64       /* maximum signed long long int value */
#define LLONG_MIN   (-9223372036854775807i64 - 1)  /* minimum signed long long int value */

and:

/* minimum signed 64 bit value */
#define _I64_MIN    (-9223372036854775807i64 - 1)
/* maximum signed 64 bit value */
#define _I64_MAX      9223372036854775807i64

I just don't get it!!!

Can somebody please shed some light on this?

like image 434
user1884325 Avatar asked Jan 22 '14 22:01

user1884325


People also ask

Can we use %d for long int?

A long int typically uses twice as many bits as a regular int, allowing it to hold much larger numbers. printf and scanf replace %d or %i with %ld or %li to indicate the use of a long int. long int may also be specified as just long.

How do you make a long variable?

You can declare and initialize a Long variable by assigning it a decimal literal, a hexadecimal literal, an octal literal, or (starting with Visual Basic 2017) a binary literal. If the integer literal is outside the range of Long (that is, if it is less than Int64.

Can you cast long to int in C?

In terms of converting a ( signed ) long long datatype to an unsigned int in C and C++, you can simply cast the data between them: int main()


2 Answers

Without the LL, the compiler appears to deduce 2147483648 is a 32-bit unsigned long. Then it applies the - operator. The result is 0 - 2147483648. Since this is less than 0 and being an unsigned long t, 4294967296 is added, which is 2147483648 again. This value is then assigned to long long x.

Suggest:

long long x = -2147483648LL;
// or
long long x = -2147483647  - 1;
like image 145
chux - Reinstate Monica Avatar answered Sep 27 '22 22:09

chux - Reinstate Monica


Try assigning to -2147483648LL

see Integer constants here

like image 24
Digikata Avatar answered Sep 27 '22 22:09

Digikata