3

There's a function in a .cpp file that looks like this:

void function() {
  //...
  if (left != right)
    do_something();
}

In an unrelated header file that ends up included in that .cpp file, there's this line:

using namespace std;

I was doing some cleanups and got rid of this using namespace std everywhere, and added the missing std:: qualification. Yet the if (left != right) line doesn't compile anymore... what gives?

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313

1 Answers1

6

Well: if they tell you that using namespace std is bad, they do mean it!

It turns out that the left != right was a comparison that was left from an older version of the code, which read

void function() {
  int left, right;
  //...
  if (left != right)
    do_something();
}

Later on, the code was refactored, and the left and right locals were removed.

With using namespace std, the comparison was interpreted as if (std::left != std::right), and was always true! Because std::left and std::right are two functions, so they always compare different, and they can be compared because C++ inherits the, ahem, insanity of C, and treats functions like function pointers whenever necessary.

So yeah, if you're using namespace std, you should stop. Right now. It will happily make nonsensical code compile, without you ever knowing...

PVS-Studio can find such an error using the V1058 diagnostic: https://godbolt.org/z/YZTwhp (thank you Andrey Karpov!!).

Pinging cppcheck developers: you might wish to flag this one. It was a doozy.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313