CodeSOD: If You Switch

Switches are great. Given a value, you can switch to different code paths based on that value. The problem is… what if you have other conditions too?

Well, Hubert's co-worker found a way around that. Here's a heavily anonymized version of the pattern.

switch(someValue) { case A: if (boolX) { case B: doStuff(); } else if (boolB) { case C: doOtherStuff(); } else { doYetMoreStuff(); } break; case D: // blah, blah }

In C++, and probably several similar languages, this compiles. Whether it should or not is irrelevant, it does. Our syntax highlighter doesn't like it, though. The truth-table for this particular statement is… odd. I whipped up a little playground for you to try it out, yourselves, but here's a quick summary:

Branch 0: A,1,1, doStuff() Branch 0: A,1,0, doStuff() Branch 1: A,0,1, doOtherStuff() Branch 2: A,0,0, doYetMoreStuff() Branch 0: B,1,1, doStuff() Branch 0: B,1,0, doStuff() Branch 0: B,0,1, doStuff() Branch 0: B,0,0, doStuff() Branch 1: C,1,1, doOtherStuff() Branch 1: C,1,0, doOtherStuff() Branch 1: C,0,1, doOtherStuff() Branch 1: C,0,0, doOtherStuff()

Seeing it printed out makes it easier to understand what this code is doing. Case A can sometimes go down any possible branch. Cases B and C only behave like traditional switch statements. Even without the heavy anonymization, though, this would be hard to follow.

Hubert found this in existing production code during a code review. Discussion were had about the whys and wherefores.

[Advertisement] Utilize BuildMaster to release your software with confidence, at the pace your business demands. Download today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.