Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't adding sqrt() cause a conflict in C++? [duplicate]

Tags:

c++

If I write a new function that has the signature of a C library function, I expect a compile error due to the ambiguity. But, I can't understand why there is no error in the following C++ code.

#include <iostream>
#include <cmath>
using namespace std;

double sqrt(double number)
{
    return number * 2;  
}

int main( )
{
    cout << sqrt(2.3) << endl;
    cout << ::sqrt(2.3) << endl;
    cout << std::sqrt(2.3) << endl;
    return 0;
}

If I change the return type of sqrt() to int, then a compile error occurs due to the declaration ambiguity with double sqrt() in cmath. How is it possible to override double sqrt()? (Actually, all the cmath functions can be overridden, and I don't know why.)

like image 674
austin Avatar asked Oct 28 '19 16:10

austin


1 Answers

The program has undefined behaviour.

[reserved.names]
1 The C++ standard library reserves the following kinds of names:
1.1) — macros
1.2) — global names
1.3) — names with external linkage
2 If a program declares or defines a name in a context where it is reserved, other than as explicitly allowed by this Clause, its behavior is undefined.

[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.

like image 119
n. 1.8e9-where's-my-share m. Avatar answered Oct 12 '22 17:10

n. 1.8e9-where's-my-share m.