Tuesday, 30 April 2013

Using for as a brace-less scope

I commented previously on Jens Gustedt's trick of using a for construct as a brace-less scope in which additional variables may be introduced, but the disadvantage is that any enclosed break statement will apply to the abused for statements instead of a containing explicit for statement.

So I attempted to detect a the operation of a break statement in order to propagate it to an outer loop.

In the code below, highlighted lines would be inserted by a macro, the purposes is to have the inner break be propagated to the outer loop.

#include <stdio.h>

int main() {
  int a=0;
  for(a=0; a<2; a++) {
    for (int o=0; o>=0; (o==1) && break; )
      for (int i=0; !o && (o=1), i==0; o=-1, i=-1 ) {
        printf("In loop %d o=%d i=%d\n",a, o, i);
        break;
      }
  }
  printf("Finished with %d\n", a);
}

Sadly, (o==1) && break is not legal.

This works, ({ if (o==1) break; }) but sadly only for gcc.

No comments:

Post a Comment