2

"C++ Primer" (5th edition) states on page 91 the advantage of including the C++ version of a C standard library header instead of the .h version: this way the included names end up in the std:: namespace and do not pollute the global namespace.

I tried including cstdio and was surprised to observe that I can use printf() without specifying std::. Interestingly, including only iostream or only string is also sufficient to get access to a global printf(). Am I missing something?

I am compiling with g++ 4.8.2 with -Wall -Wextra -Werror -std=c++11.

AlwaysLearning
  • 7,257
  • 4
  • 33
  • 68
  • So, is there any advantage left for `` over ``? – AlwaysLearning Jun 30 '15 at 10:47
  • yes - you should use functions prefixed by std::, just to make your code more clean and explicit :) Also - hopefully at some point standard will forbid global namespace pollution – Hcorg Jun 30 '15 at 10:50
  • I missed the other post and it does answer the question. Should I delete my post or leave it? – AlwaysLearning Jun 30 '15 at 10:53
  • @MeirGoldenberg With some luck the next guy who misses the other post will find yours. That's why duplicates are linked and not deleted :) – Quentin Jun 30 '15 at 11:25

1 Answers1

1

It is unspecified whether <cfoo> also puts the names into the global namespace. All C library names are reserved in the global namespace in C++.

[extern.names]/3:

Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace.

To restate this:

  • in order to use a name in std, you must include the correct header.
  • You must not redefine any names from the C standard library in the above contexts.
  • Nothing says whether any particular names from the C standard library are declared (unless you explicitly include the deprecated header <foo.h>).
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084