在C++的for循环中声明结构体是否合法?

4

我刚在Gcc编译器中尝试了以下程序。我想知道,在for循环中声明结构体,且在GCC中能正常工作。

#include <iostream>

int main()
{
      int i = 0;
      for(struct st{ int a{9}; }t; i<3; i++)
            std::cout<<t.a<<std::endl;
}

那么,在 for 循环中声明结构体是否合法?

演示


4
你的演示程序是使用C++(17)编译的,不是C语言!你的代码在C语言中是非法的并且也无法编译 - andreee
那是C++,不是C。 - drRobertz
这不是一个 C 程序;而且您的 DEMO 链接使用了 g++ -std=gnu++17。 - Jens
你尝试过它,发生了什么事? - user207421
在C语言中,据我所知,你不能在for(...)内部声明变量。 - Gladaed
1个回答

7

是的,从C99开始,在for循环的clause-1中(带有初始化程序)声明变量是合法的。现在让我们将您的C++代码转换为C代码:

$ cat x.c
#include <stdio.h>

int main(void) {
    for (struct { int a;} t = { 0 }; t.a < 3; ++t.a) {
        printf("%d\n", t.a);
    }
    return 0;
}
$ gcc -Wall -Wextra -std=c99 x.c
$ ./a.out
0
1
2

相关C99:

6.8.5.3 for语句

1 The statement

for ( clause-1 ; expression-2 ; expression-3 ) statement

behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-1 is a declaration, the scope of any variables it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.133)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接