News for hackers. Stuff that matters.
Re:Recommendations about coding in C++ by to3m on Sunday February 19, 2017 @04:36PM (#13682146)
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 */;

There are no comments on this comment yet.