The following c++ code does not compile:
int main() {
double a = abs(5.1);
return 0;
}
It complains that abs is not defined, of course. But the following does compile:
#include <iostream>
int main() {
std::cout << abs(5.1) << std::endl;
std::cout << abs(-5.1) << std::endl;
return 0;
}
It outputs two 5’s (not 5.1’s). This is bad for lots of reasons. First, abs is such a natural and common function that I use it all the time, but the int part is almost never what I want returned. Second, it’s much too easy for me (or people using my code) to just write abs and not notice that it compiles but does the wrong thing, because I’m (they’re) really good at overlooking warnings. Third, I just plain don’t understand why iostream bothers defining an abs function anyway. Fourth, I really don’t understand why it goes into the global namespace.
Is there any way I can prevent this objectionable abs function from going into my global namespace?
If it matters, I’m using
gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.6)
Most likely
iostreamincludesstdlib.hto do some of its work. This is the C version of the header which declaresabsforintonly in the global namespace (in C you had to usefabsfordoublevalues).I’m not aware of any specific way to keep
absfrom being included that way but I do know that g++ 4.5 is much better at not having excess stuff brought in by basic includes likeiostreamandstring.It may also be possible to get a warning that the double is being truncated to int (EDIT: yes, use
-Wconversionto warn).