C语言 C auto 关键字在哪里使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2192547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where is the C auto keyword used?
提问by Vijay
In my college days I read about the autokeyword and in the course of time I actually forgot what it is. It is defined as:
在大学时代,我阅读了有关auto关键字的信息,但随着时间的流逝,我实际上忘记了它是什么。它被定义为:
defines a local variable as having a local lifetime
将局部变量定义为具有局部生命周期
I never found it is being used anywhere, is it really used and if so then where is it used and in which cases?
我从来没有发现它在任何地方使用,它是否真的使用过,如果是,那么它在哪里使用,在哪些情况下使用?
采纳答案by Mehrdad Afshari
autois a modifier like static. It defines the storage class of a variable. However, since the default for local variables is auto, you don't normally need to manually specify it.
auto是一个修饰符,如static. 它定义了变量的存储类。但是,由于局部变量的默认值是auto,您通常不需要手动指定它。
This pagelists different storage classes in C.
此页面列出了 C 中的不同存储类。
回答by Jerry Coffin
If you'd read the IAQ(Infrequently Asked Questions) list, you'd know that auto is useful primarily to define or declare a vehicle:
如果您阅读了IAQ(不常见问题)列表,您就会知道 auto 主要用于定义或声明车辆:
auto my_car;
A vehicle that's consistently parked outdoors:
一直停在户外的车辆:
extern auto my_car;
For those who lack any sense of humor and want "just the facts Ma'am": the short answer is that there's never any reason to use autoat all. The only time you're allowed to use autois with a variable that already has autostorage class, so you're just specifying something that would happen anyway. Attempting to use autoon any variable that doesn't have the autostorage class already will result in the compiler rejecting your code. I suppose if you want to get technical, your implementation doesn't have to be a compiler (but it is) and it can theoretically continue to compile the code after issuing a diagnostic (but it won't).
对于那些缺乏幽默感并想要“只是事实女士”的人:简短的回答是根本没有任何理由使用auto。唯一允许您使用的auto是已经具有auto存储类的变量,因此您只需指定无论如何都会发生的事情。尝试auto在没有auto存储类的任何变量上使用将导致编译器拒绝您的代码。我想如果你想获得技术,你的实现不一定是编译器(但它是),理论上它可以在发出诊断后继续编译代码(但它不会)。
Small addendum by kaz:
kaz 的小附录:
There is also:
还有:
static auto my_car;
which requires a diagnostic according to ISO C. This is correct, because it declares that the car is broken down. The diagnostic is free of charge, but turning off the dashboard light will cost you eighty dollars. (Twenty or less, if you purchase your own USB dongle for on-board diagnostics from eBay).
这需要根据 ISO C 进行诊断。这是正确的,因为它声明汽车发生故障。诊断是免费的,但关闭仪表板灯将花费您 80 美元。(二十或更少,如果您从 eBay 购买自己的 USB 加密狗用于车载诊断)。
The aforementioned extern auto my_caralso requires a diagnostic, and for that reason it is never run through the compiler, other than by city staff tasked with parking enforcement.
上述extern auto my_car还需要诊断,因此它永远不会通过编译器运行,除了负责停车执法的城市工作人员。
If you see a lot of extern static auto ...in any code base, you're in a bad neighborhood; look for a better job immediately, before the whole place turns to Rust.
如果你extern static auto ...在任何代码库中看到很多,你就处于一个糟糕的社区;在整个地方转向 Rust 之前,立即寻找更好的工作。
回答by Kaz
The autokeyword is useless in the C language. It is there because before the C language there existed a B language in which that keyword was necessary for declaring local variables. (B was developed into NB, which became C).
该auto关键字是在C语言中无用。之所以存在,是因为在 C 语言之前存在一种 B 语言,其中该关键字是声明局部变量所必需的。(B发展成NB,后来变成C)。
Here is the reference manual for B.
As you can see, the manual is rife with examples in which autois used. This is so because there is no intkeyword. Some kind of keyword is needed to say "this is a declaration of a variable", and that keyword also indicates whether it is a local or external (autoversus extrn). If you do not use one or the other, you have a syntax error. That is to say, x, y;is not a declaration by itself, but auto x, y;is.
如您所见,手册中充满了使用的示例auto。这是因为没有int关键字。需要某种关键字来说明“这是一个变量的声明”,并且该关键字还表明它是本地的还是外部的(autovs extrn)。如果您不使用其中之一,则会出现语法错误。也就是说x, y;,本身不是声明,而是声明auto x, y;。
Since code bases written in B had to be ported to NB and to C as the language was developed, the newer versions of the language carried some baggage for improved backward compatibility that translated to less work. In the case of auto, the programmers did not have to hunt down every occurrence of autoand remove it.
由于在开发语言时必须将用 B 编写的代码库移植到 NB 和 C,因此该语言的较新版本带有一些包袱,以提高向后兼容性,从而减少工作量。在 的情况下auto,程序员不必追查所有出现的情况auto并将其删除。
It's obvious from the manual that the now obsolescent "implicit int" cruft in C (being able to write main() { ... }without any intin front) also comes from B. That's another backward compatibility feature to support B code. Functions do not have a return type specified in B because there are no types. Everything is a word, like in many assembly languages.
从手册中可以明显看出,C 中现在已经过时的“隐式 int” cruft(能够在main() { ... }没有任何int前面编写)也来自 B。这是另一个支持 B 代码的向后兼容性功能。函数没有在 B 中指定的返回类型,因为没有类型。一切都是一个词,就像在许多汇编语言中一样。
Note how a function can just be declared extrn putcharand then the only thing that makes it a function that identifier's use: it is used in a function call expression like putchar(x), and that's what tells the compiler to treat that typeless word as a function pointer.
注意一个函数是如何被声明的extrn putchar,然后唯一使它成为标识符使用的函数的事情:它被用在像 的函数调用表达式中putchar(x),这就是告诉编译器将该无类型词视为函数指针的原因。
回答by Michael Burr
In C autois a keyword that indicates a variable is local to a block. Since that's the default for block-scoped variables, it's unnecessary and very rarely used (I don't think I've ever seen it use outside of examples in texts that discuss the keyword). I'd be interested if someone could point out a case where the use of autowas required to get a correct parse or behavior.
在 C 中auto是一个关键字,表示变量是块的局部变量。由于这是块范围变量的默认设置,因此它是不必要的并且很少使用(我认为我从未见过它在讨论关键字的文本中的示例之外使用)。如果有人可以指出auto需要使用来获得正确解析或行为的情况,我会很感兴趣。
However, in the C++11 standard the autokeyword has been 'hiHymaned' to support type inference, where the type of a variable can be taken from the type of its initializer:
但是,在 C++11 标准中,auto关键字已被“劫持”以支持类型推断,其中变量的类型可以从其初始化器的类型中获取:
auto someVariable = 1.5; // someVariable will have type double
Type inference is being added mainly to support declaring variables in templates or returned from template functions where types based on a template parameter (or deduced by the compiler when a template is instantiated) can often be quite painful to declare manually.
添加类型推断主要是为了支持在模板中声明变量或从模板函数返回,其中基于模板参数(或在实例化模板时由编译器推断)的类型通常很难手动声明。
回答by raphnet
With the old Aztec C compiler, it was possible to turn all automatic variables to static variables (for increased addressing speed) using a command-line switch.
使用旧的 Aztec C 编译器,可以使用命令行开关将所有自动变量转换为静态变量(以提高寻址速度)。
But variables explicitly declared with autowere left as-is in that case. (A must for recursive functions which would otherwise not work properly!)
但是auto在这种情况下,显式声明的变量保持原样。(递归函数的必需品,否则将无法正常工作!)
回答by Mikhail
The autokeyword is similar to the inclusion of semicolons in Python, it was required by a previous language (B) but developers realized it was redundant because most things were auto.
该auto关键字类似于 Python 中包含的分号,以前的语言 ( B)需要它,但开发人员意识到它是多余的,因为大多数东西都是auto.
I suspect it was left in to help with the transition from B to C. In short, one use is for B language compatibility.
我怀疑它被留下来帮助从 B 到 C 的过渡。简而言之,一种用途是 B 语言兼容性。
For example in B and 80s C:
例如在 B 和 80 年代 C:
/* The following function will print a non-negative number, n, to
the base b, where 2<=b<=10. This routine uses the fact that
in the ASCII character set, the digits 0 to 9 have sequential
code values. */
printn(n, b) {
extrn putchar;
auto a;
if (a = n / b) /* assignment, not test for equality */
printn(a, b); /* recursive */
putchar(n % b + '0');
}
回答by Lewis Kelsey
autocan only be used for block-scoped variables. extern auto intis rubbish because the compiler can't determine whether this uses an external definition or whether to override the extern with an auto definition (also auto and extern are entirely different storage durations, like static auto int, which is also rubbish obviously). It could always choose to interpret it one way but instead chooses to treat it as an error.
auto只能用于块范围的变量。extern auto int是垃圾,因为编译器无法确定它是使用外部定义还是用自动定义覆盖 extern(而且 auto 和 extern 是完全不同的存储持续时间,例如static auto int,这显然也是垃圾)。它总是可以选择以一种方式解释它,而是选择将其视为错误。
There is one feature that autodoes provide and that's enabling the 'everything is an int' rule inside a function. Unlike outside of a function, where a=3is interpreted as a definition int a =3because assignments don't exist at file scope, a=3is an error inside a function because apparently the compiler always interprets it as an assignment to an external variable rather than a definition (even if there are no extern int aforward declarations in the function or in the file scope), but a specifier like static, const, volatileor autowould imply that it is a definition and the compiler takes it as a definition, except autodoesn't have the side effects of the other specifiers. auto a=3is therefore implicitly auto int a = 3
有一个功能auto确实提供了,那就是在函数内启用“一切都是 int”规则。与函数外部不同, wherea=3被解释为定义,int a =3因为赋值不存在于文件范围内,a=3是函数内部的错误,因为显然编译器总是将其解释为对外部变量的赋值而不是定义(即使有extern int a在函数或文件范围内没有前向声明),而是像static, const, volatileorauto这样的说明符暗示它是一个定义,编译器将其作为定义,除非auto没有其他说明符的副作用。auto a=3因此隐含地auto int a = 3
Also note 'autohas no effect on whether an object will be allocated to a register (unless some particular compiler pays attention to it, but that seems unlikely)'
另请注意“auto对是否将对象分配给寄存器没有影响(除非某些特定的编译器注意到它,但这似乎不太可能)”
回答by Atul Sharma
Auto keyword is a storage class (some sort of techniques that decides lifetime of variable and storage place) example. It has a behavior by which variable made by the Help of that keyword have lifespan (lifetime ) reside only within the curly braces
Auto 关键字是一个存储类(某种决定变量和存储位置生命周期的技术)示例。它有一个行为,即由该关键字的帮助创建的变量的生命周期(lifetime)仅驻留在花括号内
{
auto int x=8;
printf("%d",x); // here x is 8
{
auto int x=3;
printf("%d",x); // here x is 3
}
printf("%d",x); // here x is 8
}
回答by Mattias
autois good for saying that you do not want it to be register.
However it is often useless since the compiler will put registerwhen
neither been used and it thinks it is optimal, and it will seldom think so incorrectly, it will however often miss that registeris optimal.
auto说你不想要它是好的register。然而它通常是无用的,因为编译器会register在两者都没有被使用的时候把它放进去并且它认为它是最优的,它很少会这么认为是错误的,但是它经常会错过那个register最优的。

