On Visual Studio 2010 the following program
#include <iostream>
using std::cout;
int main()
{
cout << -2147483646 << '\n';
cout << -2147483647 << '\n';
cout << -2147483648 << '\n'; // numeric_limits<int>::min()
cout << -2147483649 << '\n';
cout << -2147483650 << '\n';
cout << "..." << '\n';
cout << -4294967293 << '\n';
cout << -4294967294 << '\n';
cout << -4294967295 << '\n'; // -numeric_limits<unsigned int>::max()
cout << -4294967296 << '\n';
cout << -4294967297 << '\n';
}
generates the following output
-2147483646
-2147483647
2147483648
2147483647
2147483646
...
3
2
1
-4294967296
-4294967297
What is going on?
Is this standard behavior or a Visual Studio bug?
Edit: As several people have pointed out, there is no such thing as a negative integer literal. See Keith Thompson’s excellent answer below for more details.
-2147483648, for example, is not an integer literal. It’s an expression consisting of a unary-operator applied to the literal2147483648.Prior to the C++ 2011 standard, C++ didn’t require the existence of any type bigger than 32 bits (C++2011 added
long long, which is at least 64 bits), so the literal2147483648was non-portable.A decimal integer literal is of the first of the following types in which its value fits:
Note that it’s never of an unsigned type in standard C++. In pre-2011 editions of the C++ standard (which didn’t have
long long int), a decimal integer literal that’s too big to fit inlong intresulted in undefined behavior — but you’re unlikely to have to worry about that. In C++2011 and later, if a decimal integer literal doesn’t fit inlong long int, then the program is "ill-formed".Some very old versions of g++ didn’t implement the C++2011 semantics. For example, g++ 4.6.1 (the version on which I based the original version of this answer) treated the literal
2147483648as a constant of typeunsigned long. (See the edit history of this question for more out-of-date information.)Here’s a small program that you can use to show how your compiler treats literals:
When I compile and execute it (with g++ 11.3.0 on 64-bit Ubuntu) I get: