Here is what works and is not undefined behavior:
unsigned int abs(const int number)
{
return (number > 0) ? number : static_cast<unsigned int>((-(static_cast<int64_t>(number))));
}
unsigned int abs(const int number)
{
const int64_t mask = number >> 31;
return (number + mask) ^ mask;
}
unsigned int abs(const int number)
{
return (number > 0) ? number : (number - 1) ^ -1;
}
This may work... it probably does, but if it does then your compiler will produce the same assembly as one of the above... but negating signed int number when its value is INT_MIN is undefined behavior as far as the standard goes. If the behavior is defined in your compiler implementation documentation, then that's a different story... but it probably isn't, so there be dragons here:
unsigned int abs(const int number)
{
return (number > 0) ? number : -number;
}
Notice they all return an unsigned? Yeah, that's different from std::abs... so keep that in mind.