12

My snippet:

auto i = -2147483648;
int j = 3;
std::swap(i, j); // Compile error about mismatched types here. 

The compiler states that the literal i is a long long. Why is that? -2147483648 fits in an int on MSVC x64.

My compiler is MSVC, target is 64 bits.

phuclv
  • 37,963
  • 15
  • 156
  • 475
P45 Imminent
  • 8,319
  • 4
  • 35
  • 78
  • 1
    related [Casting minimum 32-bit integer (-2147483648) to float gives positive number (2147483648.0)](http://stackoverflow.com/q/11536389/995714), [Why is 0 < -0x80000000?](http://stackoverflow.com/q/34182672/995714), [(-2147483648> 0) returns true in C++?](http://stackoverflow.com/q/14695118/995714) – phuclv Jan 11 '16 at 16:19
  • 1
    For fun, look up your compiler's definition of `INT_MIN`. Even when `INT` is 32 bits, `INT_MIN` is not defined as `(-2147483648)` for precisely this reason. – MSalters Jan 11 '16 at 20:50
  • 1
    I'm hesitant to close this a duplicate of the last question; opinions welcome. – MSalters Jan 11 '16 at 20:53
  • related: http://stackoverflow.com/questions/34724320/why-does-the-smallest-int-%E2%88%922147483648-have-type-long – Adrian McCarthy Jan 11 '16 at 22:46

1 Answers1

29

Contrary to popular belief, -2147483648 is not a literal: C++ does not support negative literal values.

It is, in fact, a compile-time evaluable constant expression consisting of a unary negation of the literal 2147483648.

On MSVC x64, which has 32 bit ints and longs, 2147483648 is too big for either of those so it fails over to the long long type that you observe.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • @P45Imminent, we had the same question in C tag 30 minutes ago, closed as duplicate. – SergeyA Jan 11 '16 at 15:49
  • @P45Imminent, this is the question I am talking about: http://stackoverflow.com/questions/34724320/printf-d-or-i-minimum-int-value/34724513?noredirect=1#comment57195717_34724513 – SergeyA Jan 11 '16 at 15:51
  • I've just upvoted that one. By the way, I'm not at school. I work with Bathsheba. But that one seems to convert to a long. – P45 Imminent Jan 11 '16 at 15:52
  • That is a platform difference. If the platform has a 32 bit int and a 64 bit long (as 64-bit linux does) then 2147483648 will be interpreted as a long. If the platform has a 32 bit long (as 64 bit windows does) then 2147483648 will be interpreted as a long long (long long is required by the standard to be at least 64 bit). – plugwash Jan 11 '16 at 19:57
  • The question itself actually contained a big clue that the OP missed, which is the claim that `i` is a literal! – Lightness Races in Orbit Jan 11 '16 at 21:38