Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...