As I found out that I can use only numerical values in C++'s switch
statements, I thought that there then must be some deeper difference between it and a bunch of if-else
's.
Therefore I asked myself:
switch
differ from if-elseif-elseif
in terms of runtime speed, compile time optimization and general compilation? I'm mainly speaking of MSVC here.A switch is often compiled to a jump-table (one comparison to find out which code to run), or if that is not possible, the compiler may still reorder the comparisons, so as to perform a binary search among the values (log N comparisons). An if-else chain is a linear search (although, I suppose, if all the relevant values are compile-time integral constants, the compiler could in principle perform similar optimizations).