Correct way to take absolute value of INT_MIN
Posted
by
aka.nice
on Stack Overflow
See other posts from Stack Overflow
or by aka.nice
Published on 2012-09-01T21:29:52Z
Indexed on
2012/09/01
21:38 UTC
Read the original article
Hit count: 160
c
I want to perform some arithmetic in unsigned, and need to take absolute value of negative int, something like
do_some_arithmetic_in_unsigned_mode(int some_signed_value)
{
unsigned int magnitude;
int negative;
if(some_signed_value<0) {
magnitude = 0 - some_signed_value;
negative = 1;
} else {
magnitude = some_signed_value;
negative = 0;
}
...snip...
}
But INT_MIN might be problematic, 0 - INT_MIN is UB if performed in signed arithmetic. What is a standard/robust/safe/efficient way to do this in C?
© Stack Overflow or respective owner