How does switch compile in Visual C++ and how optimized and fast is it?

后端 未结 2 866
庸人自扰
庸人自扰 2020-11-29 07:59

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

2条回答
  •  执笔经年
    2020-11-29 08:42

    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).

提交回复
热议问题