3 ms·
There are many cases where fall through switch statements are preferable, but that's almost beside the point. C is basically just portable assembler with syntac
by joshAg 14y ago
There are many cases where fall through switch statements are preferable, but that's almost beside the point. C is basically just portable assembler with syntactic sugar sprinkled on top. Assembler doesn't have less dangerous switch statements and switch statments. Assembler has branching and jumping. That break statement in c is almost literally telling the assembler to jump out of a chain of branch statements after probably returning from a jal of the function within the same case block. Adding an extra switch statement just takes the language farther away from assembler and makes compiling more complicated, which is silly since the unsafe switch statement with break statements will/should produce the exact same assembler (this is different from the difference between using if{}else{ if...} chains and using switch, which will produce different assembler code).
To make it even more fun, there are many use cases for fall through switch statements. My personal favorite is duff's device, which is an unwrapped version of a serial copy that will run faster on certain architectures than a more typical serial copy will run:
send(to, from, count)
register short to, from;
register count;
{
register n = (count + 7) / 8;
switch(count % 8) {
case 0: do { to = from++; //this is for a memory mapped register.
case 7: to = from++; // use to++ for non memory mapped registers
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);
}
}
- shurane 14y agoI thought duff's device was one of the few examples that use fall through switch statements. I was taught to use switches with blocks, because otherwise unexpected things happen.