0

I don't know why the following code prints the same number. I expect it would give me some overflow error or something else.

int a = -2147483648;
int b = -a;
cout << a << "\t" << b << endl;

It prints -2147483648 -2147483648.

Chan mankong
  • 153
  • 2
  • 6
  • 2
    see [What is undefined behaviour?](https://stackoverflow.com/a/4105123/1505939). Anything can happen. – M.M Apr 12 '19 at 02:48
  • 2
    Negating the min int value with two's compliment arithmetic is undefined behavior but this is typical of the behavior of two's compliment math. – doug Apr 12 '19 at 02:48
  • Possible duplicate of [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – Ken White Apr 12 '19 at 03:30
  • You are aware of the special attribute of that magic number, aren't you? – Yunnosch Apr 12 '19 at 04:00
  • 1
    The problem with your code is that `int` has 32 bit only, in your case. Hence, the max. possible value is `2147483647`. `-2147483648` is the one and only value which cannot be negated. (Try this with `int64_t` instead of `int` and it will work.) – Scheff's Cat Apr 12 '19 at 05:38
  • 1
    Possible duplicate of [Why the absolute value of the max negative integer -2147483648 is still -2147483648?](https://stackoverflow.com/questions/11243014/why-the-absolute-value-of-the-max-negative-integer-2147483648-is-still-2147483) – Alexey Frunze Apr 12 '19 at 05:59

0 Answers0