1

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?

Source on Wandbox

1
  • It is documented. As for reference, see this en.cppreference.com/w/cpp/language/…. (The abs can be a std::abs with using std::abs; in some implementation without side effects) Commented Dec 8, 2020 at 14:57

1 Answer 1

1

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" and extern "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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.