gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:33 25 4
gpt4 key购买 nike

我刚刚在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com