Warm tip: This article is reproduced from serverfault.com, please click

Why do I get an error in this code when using "using namespace std;" and "bits/stdc++.h"?

发布于 2020-12-03 09:03:47

Actually this code works fine in "DEV C++", but when I put it into my "Hacker-Rank" panel it gives this error "reference to function is ambiguous", although all the online compilers are giving errors...

I don't think here function overloading is somewhere interrupting, because this error mostly comes in function overloading.

#include <bits/stdc++.h>
#include <cstdio>
#include<iostream>

using namespace std;


int function(int n);

int main()
{
    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');    

    if(n<=0){
        return(0);
    }
    else{
        function(n);
    }

}
int function(int n)
{
    if (n<=9)
    {
        cout<<"experiment";
    }
    
    else{
        cout<<"Greater than 9";
    }
    return 0;
}

The error with clang is:

<source>:20:9: error: reference to 'function' is ambiguous
        function(n);
        ^
<source>:8:5: note: candidate found by name lookup is 'function'
int function(int n);
    ^
/opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/11.0.0/../../../../include/c++/11.0.0/bits/std_function.h:111:11: note: candidate found by name lookup is 'std::function'
    class function;
          ^
// ... and more ....
Questioner
fly_high
Viewed
0
Vlad from Moscow 2020-12-03 17:15:53

For starters this else code block

else{
    function(n);
}

returns nothing.

Though it is allowed but confuses readers of the program because they expect that if there is an explicit return statement in the if sub-statement then a similar return statement should be in the else sub-statement.

It seems the name function declared in the global name space conflicts with the standard name std::function due to the using directive.

using namespace std;

Write

else{
    return ::function(n);
}