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;