Home > Mobile >  C If statement before case in switch
C If statement before case in switch

Time:04-12

I am tasked to rewrite some old software for my company and found an interesting construct inside the sources.

switch(X){
    if(Y==Z){
       case A: ... break;
       case B: ... break;
    }
    case C: ... break;
    default: ...;
}

The compiler warns me, that the code inside the if statment will not be executed but while testing it just seems that the if statment is not validated, the case statments however are.

Is there any reason, maybe early C days as some of the code is over 20 years by now, why you would write a construct like that? It is in production code so it does seem to do something?

I would be thankfull for any inside why this might have been done and if I can just ignore it as the compiler seems to do.

Edit: It is also occuring multiple times, so it does not seem to be a simple error. This is what is confusing me.

Edit2: Here is the example I used for testing. I am not sure how helpful it is however the origial code is inside a 1200 line monster function so creating one from that is basically impossible.

for (int i=0; i<5;i  )
{
    switch(i)
    {
        if (i==0 || i ==1)
        {
            cout << "reached before case";
            case 0: cout << "inside case 0" << std::endl; break;
            case 1: cout << "inside case 1" << std::endl; break;
            case 2: cout << "inside case 2" << std::endl; break;
        }
        case 3: cout << "inside case 3" << std::endl; break;
        default: cout << "inside default" << std::endl;
    }
}

CodePudding user response:

Is there any reason ... why you would write a construct like that?

Only the author knows for sure (even they might not know). If there is source versioning metadata available, then associated commit message might be useful. Without more information, we can only guess what they were thinking. Some potential answers:

  • The author assumed that the condition of the if-statement would have some effect, but they were wrong and the mistake wasn't tested.
  • It's a vestigial result of some refactoring.
    • Perhaps some code was removed that used to make the statement meaningful.
    • Or perhaps it was copied from elsewhere where it did have a meaning.
    • Or perhaps there used to be a series of if-statements and there was an intention to replace them with a switch, but the change was half-assed.
  • Related