Is this always technically correct:
unsigned abs(int n)
{
if (n >= 0) {
return n;
} else {
return -n;
}
}
It seems to me that here if -INT_MIN > INT_MAX, the "-n" expression could overflow when n == INT_MIN, since -INT_MIN is outside the bounds. But on my compiler this seems to work ok... is this an implementation detail or a behaviour that can be relied upon?
Longer version
A bit of context: I'm writing a C++ wrapper for the GMP integer type (mpz_t) and taking inspiration for the existing GMP C++ wrapper (called mpz_class). When handling addition of mpz_t with signed integers there is code like this:
static void eval(mpz_ptr z, signed long int l, mpz_srcptr w)
{
if (l >= 0)
mpz_add_ui(z, w, l);
else
mpz_sub_ui(z, w, -l);
}
In other words, if the signed integer is positive, add it using the routine of unsigned addition, if the signed integer is negative add it using the routine of unsigned subtraction. Both *_ui routines take unsigned long as last arguments. Is the expression
-l
at risk of overflowing?
See Question&Answers more detail:os