while(...){ ... }else ...

Jens Bauer via Digitalmars-d digitalmars-d at puremagic.com
Sun Jan 18 15:16:11 PST 2015


I'd like to give an example on a different use of the same 
feature:

while(length--)
{
     *d++ = *s++;
}
if(length == -1)  /* the programmer will need to know the value 
of length here. */
{
     /* handle case where length was exactly 0, it's now -1 */
}

would become:

while(length--)
{
     *d++ = *s++;
}
otherwise
{
     /* handle case where length was exactly 0, it's now -1 */
}

---
A pseudo-assembly language version of a normal while-loop:

     bra wstart   /* this usually cost (something like) a 
clock-cycle to start */
while:
     copy.b s+,d+
wstart:
     sub length,#1
     bcc while
  wend:

---
Different version of the above:

     sub length,#1
     bcs wend
while:
     copy.b s+,d+
     sub length,#1
     bcc while
wend:
---
A pseudo-assembly language version of the 'otherwise' while-loop:
     sub  length,#1
     bcs  otherwise
while:
     copy.b s+,d+
     sub length,#1
     bcc while
     bra wend
otherwise:
     /* handle zero-length */
wend:

-These are not real good examples, though. However, they do show 
that the compiler would know that it can safely optimize the 
expression-test, and almost for free get the 'otherwise', which 
would cost only little extra CPU-time.


More information about the Digitalmars-d mailing list