Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negation of -2147483648 not possible in C/C++?

Tags:

c++

c

integer

#include <iostream>
#include <stdlib.h>

int main(int argc, char *argv[])
{

  int num=-2147483648;
  int positivenum=-num;
  int absval=abs(num);

  std::cout<<positivenum<<"\n";
  std::cout<<absval<<"\n";

  return 0;
}

Hi I am quite curious why the output of the above code is

-2147483648
-2147483648

Now I know that -2147483648 is the smallest represntable number among signed ints, (assuming an int is 32 bits). I would have assumed that one would get garbage answers only after we went below this number. But in this case, +2147483648 IS covered by the 32 bit system of integers. So why the negative answer in both cases?

like image 271
smilingbuddha Avatar asked Dec 03 '11 23:12

smilingbuddha


4 Answers

But in this case, +2147483648 IS covered by the 32 bit system of integers.

Not quite correct. It only goes up to +2147483647. So your assumption isn't right.

Negating -2147483648 will indeed produce 2147483648, but it will overflow back to -2147483648.

Furthermore, signed integer overflow is technically undefined behavior.

like image 158
Mysticial Avatar answered Oct 10 '22 08:10

Mysticial


The value -(-2147483648) is not possible in 32-bit signed int. The range of signed 32-bit int is –2147483648 to 2147483647

like image 30
Anthony Blake Avatar answered Oct 10 '22 09:10

Anthony Blake


Ahhh, but its not... remember 0, largest signed is actually 2147483647

like image 2
MattJenko Avatar answered Oct 10 '22 08:10

MattJenko


Because the 2's complement representation of signed integers isn't symmetric and the minimum 32-bit signed integer is -2147483648 while the maximum is +2147483647. That -2147483648 is its own counterpart just as 0 is (in the 2's complement representation there's only one 0, there're no distinct +0 and -0).

Here's some explanation.

A negative number -X when represented as N-bit 2's complement, is effectively represented as unsigned number that's equal to 2N-X. So, for 32-bit integers:
if X = 1, then -X = 232 - 1 = 4294967295
if X = 2147483647, then -X = 232 - 2147483647 = 2147483649
if X = 2147483648, then -X = 232 - 2147483648 = 2147483648
if X = -2147483648, then -X = 232 + 2147483648 = 2147483648 (because we only keep low 32 bits)

So, -2147483648 = +2147483648. Welcome to the world of 2's complement values.

like image 1
Alexey Frunze Avatar answered Oct 10 '22 07:10

Alexey Frunze