0

Why making an int -2147483648 to positive overflow int.

int x = -2147483648;
int num;
if(x<0)
{
   num = -x; //overflow here
}

For ex:below both x and y are same.

int x = -2147483648;
cout<<x<<endl;
int y = -x;
cout<<x<<endl;

Output:
-2147483648
-2147483648
Sanjeev
  • 115
  • 7
  • 2
    Because it doesn't fit in a 32 bit signed int? – Kevin Jan 24 '21 at 16:43
  • 3
    The valid range for a 32 bit integer is -2147483648 to 2147483647. `2147483648` is too large for a 32 bit signed int. – drescherjm Jan 24 '21 at 16:51
  • Note that before C++20 the official rules for the results of signed integer overflow are that [there are no rules](https://en.cppreference.com/w/cpp/language/ub) – user4581301 Jan 24 '21 at 17:10
  • @drescherjm How it is one greater while negative than for positive . Suppose 2 bit integer.. 00 => 0, 01 => 1, 10 => 2, 11 => 3, the same for negative max it can go to -3 , or in this range can be -4 to 3 . – Sanjeev Jan 24 '21 at 17:11
  • [Here is a neat question on what happens in c++20](https://stackoverflow.com/questions/57363324). TL;DR version: This is still UB. – user4581301 Jan 24 '21 at 17:21
  • 5
    @sanjeev there’s always one more negative than positive. So a 3 bit signed number would be -4 to 3. This is because there are an even number of total representable numbers and zero has to take one of them. This leads to having an odd number of representations left which means you can’t have equal number of positive and negative numbers. This is called twos-complement. An alternate but generally unused representation is sign/magnitude which does have the same range but can also represent negative zero. – Mike Vine Jan 24 '21 at 17:27
  • ***How it is one greater while negative than for positive*** Because there is 1 zero not 2. – drescherjm Jan 24 '21 at 17:28
  • Related C++ 'joke': `cout << abs(INT_MIN) << endl;`. – Adrian Mole Jan 24 '21 at 17:30
  • @ Mike Vine Thanks got your point. For someone like me below link can also be useful to understand https://stackoverflow.com/questions/1049722/what-is-2s-complement – Sanjeev Jan 24 '21 at 17:52

0 Answers0