This code:
#include <stdlib.h> // int abs(int);
int abs(int i = 0) { return 42; }
int main() {
return abs(1); // Returns 42
}
Returns 42
.
The compiler picks the overloaded C++ function. I tested this on many versions of g++/clang. Can I rely on this behaviour? Is it documented anywhere?
You get undefined behavior by doing that.
[extern.names]
4 Each function signature from the C standard library declared with external linkage is reserved to the implementation for use as a function signature with both
extern "C"
andextern "C++"
linkage, or as a name of namespace scope in the global namespace.
int abs(int)
is exactly one such function signature. You tread on the standard library here, and the behavior of the program is undefined.
You may not define such an abs
function in the global namespace.