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

标签 c++ for-loop structure declaration

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

DEMO

最佳答案

是的,在 for 循环(从 C99 开始)的子句 1 中声明(带有初始值设定项)是合法的。让我们将您的 C++ 转换为 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)

关于c++ - 在 C++ 的 for 循环中声明结构是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50582373/

相关文章:

c - 如何使用结构定义 C 数据类型来存储有理数(两个数字的分数)?

c - 原始代码和修改后的代码有什么区别?

c++ - 将 FILETIME 转换为字符串,否则

java - For 循环将自定义对象添加到 arraylist n 次 - Java8

c++ - Qt QWidget隐藏动画

java - 如何编写程序根据数学运算顺序进行计算? ( java )

python - "Pythonic"for 循环整数 0 到 k-1 除了 i

mysql - 如何破译这个mysql数据的结构?

c++ - 内存集区别?

c++ - 实现C++ 20 bidirectional_iterator概念