为什么在 C++ 中使用 <cstdio> 而不是 <stdio.h> 时 "std::printf" 和 "printf" 都编译?

Why do both "std::printf" and "printf" compile when using <cstdio> rather than <stdio.h> in C++?

据我所知,cxyz 形式的 headers 与 xyz.h 相同,唯一的区别是 cxyz 放置了 [=19] 的所有内容=] 在命名空间 std 下。为什么以下程序在 GCC 4.9 和 clang 6.0 上都能编译?

#include <cstdio>

int main() {
    printf("Testing...");
    return 0;
}

和第二个程序:

#include <cstdio>

int main() {
    std::printf("Testing...");
    return 0;
}

FILE 结构也是如此:

FILE* test = fopen("test.txt", "w");

std::FILE* test = std::fopen("test.txt", "w");

两者都有效。

直到现在,我一直认为使用 cstdiocstring 等比 non-namespaced 更好。但是,以上两个程序中哪个是更好的实践?

其他 C 函数也是如此,例如 memset(来自 cstring)、scanf(也来自 cstdio)等

(我知道有些人会问为什么我在 C++ 程序中使用 C IO;这里的问题不是特定的 C IO,而是这段代码是否应该在调用之前没有特别指定 std:: 的情况下编译命名空间 C 函数。)

该标准还允许编译器将名称注入全局命名空间。

这样做的一个原因是它允许 <cstdio> 的实现是:

#include <stdio.h>

namespace std
{
    using ::printf;
    using ::fopen;
    // etc.
}

因此 compiler/library 供应商不必编写和维护那么多代码。

在您自己的代码中,始终使用 std::using namespace std; 等,以便您的代码可移植到不将名称注入全局命名空间的编译器。