Search code examples
c++namespacesdoublestd

Why "using namespace std;" gives different result when dealing with doubles in C++?


Today, I was trying to answer this post (regarding checking whether a triangle can be constructed), when I encountered a weird result.

With the test of 15.15 35.77 129.07, this piece of code:

#include <iostream>
using namespace std;

const double e = 0.000001;

void f(double a, double b, double c)
{
    if (abs(180 - (a+b+c)) > e) {cout << "test"; }
}

int main()
{
    double a,b,c; cin >> a >> b >> c;
    f(a,b,c);
}

prints test as normal, while this:

#include <iostream>
const double e = 0.000001;

void f(double a, double b, double c)
{
    if (abs(180 - (a+b+c)) > e) {std::cout << "test"; }
}

int main()
{
    double a,b,c; std::cin >> a >> b >> c;
    f(a,b,c);
}

does not. The only difference is the using namespace std; line (and when I added using namespace std; to the second piece of code, as expected, it ran normally).

I've read a lot of post regarding using namespace std; over time:

but it seems that the only things using namespace std; do is cut some corners, in exchange of occasional conflicts of name of classes/variables/namespaces (the point that is brought up most when debating about whether to use it).

I did find 1 relevant post : Why does g++ (4.6 and 4.7) promote the result of this division to a double? Can I stop it? , but I didn't find anymore info elsewhere.

So what I'm I missing here?

-- Some machine info:

  • Windows 10, 64 bit
  • Code::Blocks 20.03
  • gcc/g++ 6.3.0

Solution

  • You do have a name conflict: int abs(int) versus double std::abs(double).

    With using namespace std;, abs(180 - (a+b+c)) finds both and std::abs is a better match.

    Without using namespace std;, abs(180 - (a+b+c)) only finds the former and a conversion to int is necessary, hence the observed behaviour.

    What you really want is:

    #include <iostream>
    const double e = 0.000001;
    
    void f(double a, double b, double c)
    {
        if (std::abs(180 - (a+b+c)) > e) {std::cout << "test"; }
    }
    
    int main()
    {
        double a,b,c; std::cin >> a >> b >> c;
        f(a,b,c);
    }