Suppose I have N different integral values known at compile time, V_1 through V_N. Consider the following structures:
const int x = foo();
switch(x) {
case V_1: { /* commands for V_1 which don't change x */ } break;
case V_2: { /* commands for V_1 which don't change x */ } break;
/* ... */
case V_N: { /* commands for V_1 which don't change x */ } break;
}
versus
const int x = foo();
if (x == V_1) { /* commands for V_1 which don't change x */ }
else if (x == V_2) { /* commands for V_2 which don't change x */ }
else ...
else if (x == V_N) { /* commands for V_N which don't change x */ }
Do modern C++ compilers treat these differently? That is, do they apply different potential optimization to these code structures? Or do they "canonicalize" them to the same for, then decide on optimizations (such as whether to form a jump table or not)?
Notes:
- By modern C++ compilers I mean mostly recent versions of GCC, clang and MSVC. ICC could also be relevant.
- Please answer regarding the maximum optimization level (
-O3
for clang and GCC) - ... but then, if the treatment of
switch
es andif-then-else
-chains is the same in some optimization levels and different in others, that's also interesting. - I'm guessing the answer might depend on the value of
N
- give thresholds if possible.