Why do both “std::printf” and “printf” compile when using <cstdio> rather than <stdio.h> in C++? [duplicate]

限于喜欢 提交于 2019-11-28 04:50:24

问题


To my knowledge, headers of the form cxyz are identical to xyz.h with the only difference being that cxyz places all of the contents of xyz.h under the namespace std. Why is it that the following programs both compile on GCC 4.9 and clang 6.0?

#include <cstdio>

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

and the second program:

#include <cstdio>

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

The same goes for the FILE struct:

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

and

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

both work.

Up until now, I always thought that it was better to use cstdio, cstring, etc, rather than their non-namespaced counterparts. However, which of the following two programs above are better practice?

The same goes for other C functions such as memset (from cstring), scanf (also from cstdio), etc.

(I know some people will ask why I am using C IO in a C++ program; the issue here is not specifically C IO, but whether or not this code should compile without specifically specifying std:: before calling a namespaced C function.)


回答1:


The standard permits the compiler to also inject the names into the global namespace.

One reason for this is that it permits the implementation of <cstdio> to be:

#include <stdio.h>

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

so the compiler/library vendor does not have to write and maintain so much code.

In your own code, always use std:: or using namespace std; etc. so that your code is portable to compilers which do not inject the names into global namespace.



来源:https://stackoverflow.com/questions/28227006/why-do-both-stdprintf-and-printf-compile-when-using-cstdio-rather-than

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!