我刚在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
循环中声明结构体是否合法?
我刚在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
循环中声明结构体是否合法?
是的,从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)