I'm running the following
test.cpp
#include <iostream>
#include <limits>
#include <cstdlib>
using namespace std;
int main(int argc, char** argv) {
long value = numeric_limits<long>::min();
value = abs(value);
cout << value << endl;
}
Depending on what computer I compile and run the program on, I'm getting different results.
Either I get:
abs(numeric_limits<long>::min())
Or I get:
numeric_limits<long>::min()
In the latter case, abs() doesn't seem to be performed. I'm wondering what accounts for this difference and how I should accommodate it. Should I compute abs() in a different way?
A look at a reference for std::abs
tells us what's going wrong:
Computes the absolute value of an integer number. The behavior is undefined if the result cannot be represented by the return type.
So anything can happen. It even explains below how that's the case for systems that use 2's complement for signed integers:
Notes
In 2's complement systems, the absolute value of the most-negative value is out of range, e.g. for 32-bit 2's complement type int, INT_MIN is -2147483648, but the would-be result 2147483648 is greater than INT_MAX, which is 2147483647.
If you're interested about the actual standard references it's in section 7.20.6/7.22.6 for the C99/C11 standard respectively, since the C++ only references the C standard for the functions in <cstdlib>
(with some extra overloads).