Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to declare structures in for loop of C++?

I just experimented the following program in Gcc compiler. I wondered, Declared structure in for loop and working fine in GCC.

#include <iostream>

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

So, Is it legal to declare structures in for loop?

DEMO

like image 757
msc Avatar asked Mar 06 '23 02:03

msc


1 Answers

Yes, it is legal to have a declaration (with an initializer) in a clause-1 of a for loop (starting with C99). Let's turn your C++ into C code (since your question was tagged "c" when I wrote this):

$ 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

Relevant C99:

6.8.5.3 The for statement

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)

like image 139
Jens Avatar answered Mar 15 '23 20:03

Jens