Saturday, 27 April 2013

Yet more try/finally/except

While using a for statement to declare a variable for the duration of a brace-less scope like this (requires gcc's c99 mode):

for(jmp_buf active_jmp_buf; ...; ...)

I needed a way to make sure that the loop only executed once, and really does execute once. This requires a variable that I can set after the first iteration. Where should such a variable come from? Naturally it would be declared in the same way.

for(jmp_buf active_jmp_buf, int cont=1; cont; cont=0)

However I can't make a for loop declare variables of different types, so I need 2 for loops (but they can use the variable of the outer loop).

for(int cont=1; cont; cont=0)
  for(jmp_buf active_jmp_buf; cont; cont=0) ...

And that will cause ... to be executed once, and give two scope local variables, cont which is used to terminate the loops after one iteration, and active_jump_buf which is the one we need.

So that gives:

for(int cont=1; cont; cont=0)
  for(jmp_buf active_jmp_buf; cont; cont=0)
    switch ((errno=setjmp(active_jmp_buf))) 
    if (0) {
      case 0: // first time around
           {
             ...
             ... throw(123);
             ...
           }
      break;
    } else {
      default: // break not needed for finally
           ...
    }

No comments:

Post a comment