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;
}
}
if
doesn't do anything. It might have done something in the past, for example if there was an earliercase
which was later removed. If you are using some sort of version control like git or svn you could try to "blame" the code and find out who wrote it, then ask them what their intention was. – Scandalizeif
existed before theswitch
did. But aswitch
behaves very much like agoto
in this regard, even in old versions of C++. This code requires thatY==Z
can compile, but the comparison is never made at runtime. – Pourparlerswitch
, like Duff's device. So it could be an attempt at an optimization. But it's just as likely IMO that it's just an old bug (syntactically valid, but semantically incorrect) that older compilers didn't warn about. – Disunity