C99:我可以在“for”块的开头声明变量吗?
以下代码根据 C99 合法吗?
...
for(....) {
int x = 4;
...
}
...
您可以假设在第 3 行之前变量 x 从未被声明过。
到目前为止我只发现了以下内容,但我认为这还不够:
块允许将一组声明和语句分组为一个语法单元。 具有自动存储期限和可变长度的对象的初始值设定项 具有块作用域的普通标识符的数组声明符被评估并且值是 存储在对象中(包括在没有对象的情况下存储不确定值) 初始化器)每次按照执行顺序到达声明时,就好像它是一个 语句,并在每个声明中按照声明符出现的顺序排列。
从该 PDF 的第 145 页开始。
Is the following code legal according to C99?
...
for(....) {
int x = 4;
...
}
...
You can assume that before line 3 the variable x was never declared.
Until now I have only found the following, but I dont think that this is enough:
A block allows a set of declarations and statements to be grouped into one syntactic unit.
The initializers of objects that have automatic storage duration, and the variable length
array declarators of ordinary identifiers with block scope, are evaluated and the values are
stored in the objects (including storing an indeterminate value in objects without an
initializer) each time the declaration is reached in the order of execution, as if it were a
statement, and within each declaration in the order that declarators appear.
From page 145 of that PDF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这在 C99 和 C89 中都是合法的。
看 6.8.2 ,它定义了复合语句
This is legal in both C99 and C89.
Look at 6.8.2 , which defines compound statement
是的,您可以在 C99 中的任何位置声明或定义变量(在 C89 中的块的开头)。
你说:
即使之前已声明过,您也可以声明一个具有相同名称的 new 变量。这样做会阻止您访问该块中的旧变量。
我从未尝试过C99 中的以下内容我真的不知道会发生什么:)
当我可以访问(几乎)C99 编译器时,我会尝试
C99 随心所欲地声明/定义变量的功能并不是让我想要更改的功能:)
Yes, you can declare or define a variable anywhere you want in C99 (at the start of a block in C89).
You said:
Even if it was previously declared, you could declare a new variable with the same name. Doing that prevents you from accessing the old variable within that block.
I've never tried the following in C99. I really don't know what happens :)
I'll try later, when I get access to a (almost) C99 compiler
The C99 feature of declaring/defining variables wherever one wants is not a feature that makes me want to change :)
是的,您可以在任何块的开头创建一个变量。每次进入块时都会初始化变量在 C++ 中,您可以在块内的任何位置创建它们。
Yes, you can create a variable at the beginning of any block. The variable is initialised each time the block is entered In C++, you can create them anywhere within the block.
是的,这在 C99 中是合法的,但不允许您在块之后访问“x”。尝试访问超出其范围的“x”将是未定义行为。
Yeah this is legal in C99 but you are not allowed to access 'x' after the block.It would be Undefined Behaviour trying to access 'x' beyond its scope.