Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

language lawyer - When using C headers in C++, should we use functions from std:: or the global namespace?

C is somewhat, not exactly, a subset of C++. So we can use most of the C functions/headers in C++ by changing the name a little bit (stdio.h to cstdio, stdlib.h to cstdlib).

My question is actually kind of semantic. In C++ code (using newest version of GCC compiler), I can call printf("Hello world!"); and std::printf("Hello world!"); and it works exactly the same. And in the reference I am using it also appears as std::printf("Hello world!");.

My question is, is it preferred to use std::printf(); in C++? Is there a difference?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the C++11 Standard (emphasis mine):

D.5 C standard library headers [depr.c.headers]

  1. For compatibility with the C standard library ...
  2. Every C header, each of which has a name of the form name.h, behaves as if each name placed in the standard library namespace by the corresponding cname header is placed within the global namespace scope. It is unspecified whether these names are first declared or defined within namespace scope (3.3.6) of the namespace std and are then injected into the global namespace scope by explicit using-declarations (7.3.3).
  3. Example: The header <cstdlib> assuredly provides its declarations and definitions within the namespace std. It may also provide these names within the global namespace. The header <stdlib.h> assuredly provides the same declarations and definitions within the global namespace, much as in the C Standard. It may also provide these names within the namespace std.

Using the ?name.h? headers is deprecated, they have been identified as candidates for removal from future revisions.

So, I would suggest to include the ?cname? headers and to use the declarations and definitions from the std namespace.

If you have to use the ?name.h? headers for some reasons (it's deprecated, see above), I would suggest to use the declarations and definitions from the global namespace.

In other words: prefer

#include <cstdio>

int main() {
    std::printf("Hello world
");
}

over

#include <stdio.h>

int main() {
    printf("Hello world
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...