Beware, I am talking about ::abs()
, not std::abs()
According to the cplusplus.com website, abs
is supposed to behave differently for the stdlib.
h C version, if you include <cmath>
Here is an extract from the this page (which deals with ::abs
, not std::abs
):
double abs (double x);
float abs (float x);
long double abs (long double x);
Compute absolute value
/*
Returns the absolute value of x: |x|.
These convenience abs overloads are exclusive of C++. In C, abs is only declared
in <cstdlib> (and operates on int values).
The additional overloads are provided in this header (<cmath>) for the integral types:
These overloads effectively cast x to a double before calculations
(defined for T being any integral type).
*/
Really???
I have been bitten by this when porting a program to a new platform, since different compilers and standard libraries implementation differ here.
Here is my sample program:
#include <iostream>
//#include <stdlib.h>//Necessary inclusion compil under linux
//You can include either cmath or math.h, the result is the same
//#include <cmath>
#include <math.h>
int main(int argc, const char * argv[])
{
double x = -1.5;
double ax = std::abs(x);
std::cout << "x=" << x << " ax=" << ax << std::endl;
return 0;
}
And here is the result under MSVC 2010:
- No compilation warning is emitted under MSVC 2010, and the program will compile even if you do not include neither math.h nor
stdlib.h
: it seems like math.h
and stdlib.h
are always included whatever you do
- The program output is:
x=-1.5 ax=1.5
(seemingly correct according to the reference)
Now here is the result under OSX:
- No compilation warning is emitted, even with the
-Wall
flag (the double to int cast is not signaled)! The result is the same if you replace g++
by llvm-g++
. The inclusion of math.h
or cmath
is not required for the compilation.
- The program output is:
x=-1.5 ax=1
And finally the result under Linux:
- The program will not compile if
stdlib.h
is not included (at last, one compiler that does not include stdlib
automatically). No compilation warning is emitted for the double -> int cast.
- The program output is:
x=-1.5 ax=1
No clear winner here. I know that an obvious answer is "prefer std::abs
to ::abs
", but I wonder:
- Is the cplusplus.com website right here when it says that
abs
should automatically provide double version outside of the std
namespace?
- Are all compiler and their standard libraries wrong here except MSVC (although it includes
math.h
silently)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…