Anoying problem, but what else can be done?

BCS ao at pathlink.com
Sat Feb 3 11:02:31 PST 2007


this fails

foreach(i, j; Tuple!(1,2,3,4)
{
  loopLable: while(test())
  {
    while(otherTest())
    {
      if(lastTest())
        break loopLabel;
      else
        continue  loopLabel;
    }
  }
}

The reason is that loopLabel is used once for each iteration of the foreach, 
which is unrolled. Seeing as labels have functions scope, this is an error.

the solution is a take on a duff's device:

switch(-1)
{
case -1:
  foreach(i, j; Tuple!(1,2,3,4))
  {
    case i*2:;

        // BTW should "break case i;" work?
    while(test())
    {
      while(otherTest())
      {
        if(lastTest())
          goto case i*2+1;  // goto end of loop
        else
          goto case i*2;    // goto start of loop
      }
    }

    case i*2+1:;
  }
}


Yuck!! And it gets worse if you try to nest it.

A better solution would be to define that labels have function scope from 
a syntactic standpoint, meaning that the first code would be valid because, 
while the labels references more than one location in the final program, 
it only occurs onces in the code. This would be somewhat bad but only because 
you can't jump from one iteration to the next (IIRC the switch/case/goto 
case can).

A better solution would be name:number labels (I'll use the "@" for this 
but the syntax is irrelevant)

foreach(i, j; Tuple!(1,2,3,4))
{
  loopLable at i: while(test())  // different label each time
  {
    while(otherTest())
    {
      if(nextTest())
        break loopLabel at i;      // ok, unique label
      if(lastText())
        continue  loopLabel at i;  // ditto

      static if(i>1) goto loopLabel@(i-1); // math on number ok
    }
  }
}

It also eliminates the problem of having to do math on case numbers if you 
have more than one place in the loop you want to jump to.

foreach(i, j; Tuple!(1,2,3,4))
{
  Lable at i: 
  if(jump()) goto Label at i;

  Next at i:
  if(jump()) goto Next at i;
}

Anyway, I'm not sure I like any of these, what do you all think of them?





More information about the Digitalmars-d mailing list