Correct way to take absolute value of INT_MIN

In the negative case, take some_signed_value+1. Negate it (this is safe because it can't be INT_MIN). Convert to unsigned. Then add one;


Conversion from signed to unsigned is well-defined: You get the corresponding representative modulo 2N. Therefore, the following will give you the correct absolute value of n:

int n = /* ... */;

unsigned int abs_n = n < 0 ? UINT_MAX - ((unsigned int)(n)) + 1U
                           : (unsigned int)(n);

Update: As @aka.nice suggests, we can actually replace UINT_MAX + 1U by 0U:

unsigned int abs_n = n < 0 ? -((unsigned int)(n))
                           : +((unsigned int)(n));

Tags:

C