Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch Statement: Is the logic different in C v/s. other languages like Java?

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?

like image 881
dev Avatar asked May 28 '15 17:05

dev


2 Answers

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.

like image 187
GettnDer Avatar answered Sep 25 '22 06:09

GettnDer


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 search

An analogous technique is used by GCC:

  • O(1) jump table if compact with *%rax
  • O(log(n)) else if binary search otherwise

Where the definition of compact can be found at:

  • Java: https://stackoverflow.com/a/31032054/895245
  • GCC: How Switch case Statement Implemented or works internally?

To observe that, just decompile minimal test cases:

  • in Java with javap
  • in C with 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;
};