Switch and If Statement in C/C++

Consider this example:

void send(int *to, int *from, int count)
{
  int n = (count+7)/8;
  switch(count%8) {
case 0: do{*to++ = *from++;
case 7:    *to++ = *from++;
case 6:    *to++ = *from++;
case 5:    *to++ = *from++;
case 4:    *to++ = *from++;
case 3:    *to++ = *from++;
case 2:    *to++ = *from++;
case 1:    *to++ = *from++;
    } while(--n > 0);
  }
}

What does it do?

Essentially all ‘case’s are just like the label in the goto statement. Although switch statement is the enclosing scope in the lexical sense, the do while statement is the real enclosing scope of the bulk of the code. Switch is merely a router to provide several entrances into the do while statement. Next time, when you have to decide between using switch or if statement, keep this example in mind.

Reference:
1. Duff’s device

Leave a Comment