Search code examples
cfor-loopcurly-braces

Is for ({statements;}; condition; {statements;}) legal C?


Bad style notwithstanding, is it legal C to have a for loop with braces inside the parens? Like this:

char *a = "a ";
char *b = "b ";

for ( { int aComesFirst = 1;
        char *first = a;
        char *second = b;
      };
      aComesFirst >= 0;
      { aComesFirst--;
        swap(first, second);
      } )
{
  printf("%s%s\n", first, second);
}

If something along those lines is possible, am I supposed to put a semicolon after the first close braces, or would that add an empty statement?

I do realize that it is stylistically better to move the char* declarations outside the for loop and the swap to the end of the inside of the loop. But style is not the point of this question, I just want to know if putting braces inside the parens is possible.


Solution

  • I've answered this before… this can easily be made legal in C or C++ by adding a local struct type. It's generally poor style, though.

    char *a = "a ";
    char *b = "b ";
    
    for ( struct loopy {
            int aComesFirst;
            char *first;
            char *second;
          } l = { 1, a, b }; /* define, initialize structure object */
    
          l.aComesFirst >= 0; /* loop condition */
    
          l.aComesFirst--, /* loop advance */
          swap(l.first, l.second)
        )
    {
      printf("%s%s\n", l.first, l.second);
    }