3 ms·
No, they're not inherently repeated blocks of code. You can repeat bits of code if you like, but for many common cases you have options. 1. both cases have ide
by to3m 10y ago
No, they're not inherently repeated blocks of code. You can repeat bits of code if you like, but for many common cases you have options.
1. both cases have identical code: just fall through from one to the next
case A:
case B:
// code for A and B
break;
2. one case's code is a prefix of the other: have the first case first, let it do its thing, then fall through to the second case
case A:
// code for A only
case B:
// code for A and B
break;
3. both cases have a shared suffix; have them separate, then use a goto to get to the suffix part.
case A:
// code for A only
goto AB;
case B:
// code for B only
AB:
// code for A and B
break;
4. code is somehow parameterized by the switched expression - just reuse it in the code however you need to. This is the most flexible, of course, as it lets you do anything you like.
switch(x) {
case A:
case B:
printf("value is: %d\n",important_array[x]);
if(x==A) /* something */;
} else if(x==B) /* something else */;