I am going through this tutorial on C programming. It says:
The switch-statement is actually entirely different(from other languages) and is really a "jump table". Instead of random boolean expressions, you can only put expressions that result in integers, and these integers are used to calculate jumps from the top of the switch to the part that matches that value. Here's some code that we'll break down to understand this concept of "jump tables".
But, cases of switch statement needs to be compared until a match is found(otherwise default is returned.)
How is it different from multiple if-else statements then? Or, it is just a syntactic sugar? Am I missing something important here?
It would seem that the way it is implemented is up to the compiler. How Switch case Statement Implemented or works internally?
but in general a switch statement has a pre-condition that allows the compiler to optimize it which differs from just if statements, which is that the item you are comparing against is always an integer type (char/int/long).
Other languages allow primitives that can be evaluated at compile time to be used as switch statement variables (string in C#).
But in general, other than the potential speed-up (and the fall-through that can happen if you don't break), there is no behavioural difference from a bunch of ifs.
The Java implementation is analogous to the GCC 4.8 one. javac
compiles to:
tableswitch
if the table is compact, which is O(1)lookupswitch
if not, which is an O(log(n)) binary searchAn analogous technique is used by GCC:
*%rax
Where the definition of compact can be found at:
To observe that, just decompile minimal test cases:
javap
objdump -S
Compact example:
switch (i) {
case 0:
j = 0;
break;
case 1:
j = 1;
break;
case 2:
j = 2;
break;
case 3:
j = 3;
break;
case 4:
j = 4;
break;
case 5:
j = 5;
break;
};
Non compact example:
switch (i) {
case 0:
j = 0;
break;
case 1:
j = 1;
break;
case 0x10:
j = 2;
break;
case 0x100:
j = 3;
break;
case 0x1000:
j = 4;
break;
case 0xFFFFFFF:
j = 5;
break;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With