3

The least possible value of the int type in C++ seems to be -2147483648.

Whenever my program encounters a negative integer, I want it to be converted into a positive (by multiplying it by -1):

if (n < 0) n = (-1) * n;

But, much to my chagrin, the constant compiler warning is:

runtime error: signed integer overflow: -1 * -2147483648 cannot be represented in type 'int' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior

Despite the compiler message being self explanatory, I can't find a way to overcome it.

I came across a question like how to make negative numbers into positive, but it uses library functions like fabs(), abs(). I do not want to use built-in library functions.

Moreover, Why the absolute value of the max negative integer -2147483648 is still -2147483648? shows the futility of abs() (albeit in C).

So, how to get the positive value of -2147483648 other than using this code?

if (n == -2147483648) n = 2147483648;

miken32
  • 42,008
  • 16
  • 111
  • 154
KNU
  • 2,560
  • 5
  • 26
  • 39

1 Answers1

2

Short Answer

You can't store 2147483648 in a signed 32-bit int even if you do:

if(n==-2147483648)     n=2147483648;

just try to cout the results, it will be -2147483648, so the value stored is incorrect

Long Answer

Actually, to understand why the value stored is different, you need to know how the computer stores signed int types (negative values in specific)

The easiest way to store negative values is to take the first bit as the sign indicator (0 is positive, and 1 is negative) ,but if we use this way, then there will be 0 and -0, which are the same value so we use another approach which is two's complement to store negative values and that gives us only one 0 and another number in the negative part (more than the positive)

Let's take a small example:

Let's say we need to store -2 in a signed 3-bit int (for simplicity):

  1. first, we need to convert 2 from decimal to binary which results in 010
  2. second, we need to take the two's complement of 010 to convert it from positive to negative, which results in 110 and that's how -2 stored in a signed 3-bit int

Now let's see the range of the values which a signed 3-bit int can store:

  • from -4 to 3 (negative is more than positive because we store the negative in two's complement)

Now let's try to convert -4 to 4 (which isn't in the range of a signed 3-bit int) to see what's the result stored

  1. first -4 in two's complement is 100
  2. then reverse the two's complement (to convert it to positive) by not(100)+1 -> 011+1 -> 100 which is exactly the same as -4 so the stored result is -4 and that means absolute(-4) is also -4 because 4 isn't in the range of a signed 3-bit int

and that's the same problem you have

Solution

You have some options if you really need to store 2147483648 in your variable

  1. Use a signed 64-bit int
  2. Use two variables one is an unsigned 32-bit int and the other is a boolean sign variable