0

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.

Community
  • 1
  • 1
MaviPranav
  • 335
  • 2
  • 14

1 Answers1

5

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

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Makes sense, I was mostly wondering if there was any scenario in which, despite having `using namespace std;` in the file, the `abs(int)` call was invoked whilst simply specifying `abs`. – MaviPranav Dec 27 '16 at 19:04
  • @MaviPranav, since you accepted the answer, I am assuming you got the answers you needed. If not, let me know. – R Sahu Dec 27 '16 at 21:03
  • The answer is correct, but it's still not definitive to me whether a counterexample situation can exist i.e. `abs(int)` being invoked from a call to `abs`, despite `using namespace std;` being used. – MaviPranav Dec 28 '16 at 09:19
  • Absolutely, abs(int) could be called if the #include were removed (even with using namespace std). This type of silent change when a header is removed is deadly in a larger application. Fortunately, virtually all compilers will give a warning about truncation of a double value to an integer. Yet one more reason to pay attention to compiler warnings. – Rob L Jul 15 '17 at 18:04