为什么同时使用两个"std :: printf"和"printf"使用< cstdio>时进行编译而不是< stdio.h>在C ++中? [英] Why do both "std::printf" and "printf" compile when using <cstdio> rather than <stdio.h> in C++?

查看:303
本文介绍了为什么同时使用两个"std :: printf"和"printf"使用< cstdio>时进行编译而不是< stdio.h>在C ++中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,格式为cxyz的标头与xyz.h相同,唯一的区别是cxyzxyz.h的所有内容都放在命名空间std下.为什么以下程序都在GCC 4.9和clang 6.0上编译?

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;
}

和第二个程序:

#include <cstdio>

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

FILE结构也是如此:

The same goes for the FILE struct:

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

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

都是工作.

到目前为止,我一直认为使用cstdiocstring等会比使用未命名的对应项更好.但是,下面的以下两个程序中哪个是更好的做法?

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?

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

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

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

(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.)

推荐答案

该标准允许编译器还将名称注入到全局名称空间中.

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

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

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.

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

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.

这篇关于为什么同时使用两个"std :: printf"和"printf"使用&lt; cstdio&gt;时进行编译而不是&lt; stdio.h&gt;在C ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆