Abs and using namespace std

2.2k Views Asked by At

Say I am using using namespace std (undeniably bad practice) and that I use the abs function in my code (to get the overloaded absolute function). To be specific my MWE is:

#include <cmath>
#include <iostream>
#include <stdlib.h>

using namespace std; 

int main(int argc, char* argv[]) {

 double f(-0.4);
 std::cout<<"abs(f) = "<<abs(f)<<std::endl;

}

If I comment out the using namespace std; line then the output is

abs(f) = 0

else the output is

abs(f) = 0.4

What I don't understand is how the "correct" abs function is invoked in the latter case given that even stdlib.h has an abs function that returns only int's.

In fact the second answer to this question says that using using namespace std; may not be enough. Is this true? My MWE seems to contradict this.

I am on Linux and using gcc-4.8, which is arguably the most problematic combination to resolve dependencies.

1

There are 1 best solutions below

4
On BEST ANSWER

When you use

using namespace std;

you bring the following overloads of abs into scope:

std::abs(int)
std::abs(float)
std::abs(std::complex)

The call abs(f) resolves to std::abs(float).

If you don't use

using namespace std;

there is only one abs function that you are able to use.

abs(int)

Hence, the call abs(f) resolves to abs(int).

You can still remove the using namespace std; line and use std::abs(f) instead of just abs(f).