为什么 auto a=1;用C编译? [英] Why does auto a=1; compile in C?
问题描述
代码:
int main(void)
{
auto a=1;
return 0;
}
当文件具有 .c 扩展名时,由 MS Visual Studio 2012 编译器编译而不会出错.我一直认为,当你使用.c扩展名时,编译应该按照C语法,而不是C++.此外,据我所知,自 C++11 以来,C++ 中仅允许没有类型的 auto,这意味着该类型是从初始化程序推导出来的.
gets compiled without errors by the MS Visual Studio 2012 compiler, when the file has the .c extension. I have always thought that when you use the .c extension, compilation should be according to the C syntax, and not C++. Moreover, as far as I know auto without a type is allowed only in C++ since C++11, where it means that the type is deduced from the initializer.
这是否意味着我的编译器没有坚持使用 C,或者代码实际上在 C 语言中是正确的?
Does that mean that my compiler isn't sticking to C, or is the code actually correct in C-language?
推荐答案
auto
是一个古老的 C 关键字,意思是本地范围".auto a
与 auto int a
相同,并且由于局部作用域是函数内部声明的变量的默认范围,因此它也与 int a<相同/code> 在这个例子中.
auto
is an old C keyword that means "local scope". auto a
is the same as auto int a
, and because local scope is the default for a variable declared inside a function, it's also the same as int a
in this example.
这个关键字实际上是 C 的前身 B 的遗留物,那里没有基类型:一切都是 int
、指向 int
的指针、int<的数组/code>.(*) 声明可以是
auto
或 extrn
[原文如此].C 继承了一切都是 int
"作为默认规则,因此您可以使用
This keyword is actually a leftover from C's predecessor B, where there were no base types: everything was int
, pointer to int
, array of int
.(*) Declarations would be either auto
or extrn
[sic]. C inherited the "everything is int
" as a default rule, so you could declare integers with
auto a;
extern b;
static c;
ISO C 摆脱了这一点,但为了向后兼容,许多编译器仍然接受它.如果它看起来不熟悉,那么您应该意识到相关规则正在起作用
ISO C got rid of this, but many compilers still accept it for backward compatibility. If it seems unfamiliar, then you should realise that a related rule is at work in
unsigned d; // actually unsigned int
这在现代代码中仍然很常见.
which is still common in modern code.
C++11 重用了关键字,如果有的话,很少有 C++ 程序员使用它的原始含义来进行类型推断.这在很大程度上是安全的,因为 C++98 中已经删除了来自 C 的一切都是 int
"规则;唯一出问题的是auto T a
,反正没人用过.(在他的关于语言历史的论文的某处,Stroustrup对此发表了评论,但我现在找不到确切的参考.)
C++11 reused the keyword, which few if any C++ programmers were using with the original meaning, for its type inference. This is mostly safe because the "everything is int
" rule from C had already been dropped in C++98; the only thing that breaks is auto T a
, which no-one was using anyway. (Somewhere in his papers on the history of the language, Stroustrup comments on this, but I can't find the exact reference right now.)
(*) 字符串处理很有趣:您将使用 int
数组并在每个成员中打包多个字符.B 实际上是具有不同语法的 BCPL.
(*) String handling in B was interesting: you'd use arrays of int
and pack multiple characters in each member. B was actually BCPL with different syntax.
这篇关于为什么 auto a=1;用C编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!