Jumping Switches

Jumping Switches

11 Jun 2018    

One of the reasons to prefer a switch case declaration to a bunch of if-else’s is that the compiler can generate a jump table. This is not always the case. Take the example below. Code gen can be found here: https://godbolt.org/g/V7Qdci

// Individual compares
int switch_2_cases(int val) {
    switch(val) {
        case 0:
            return 10;
        
        case 1:
            return 20;
    }

    return 0;
}

// Individual compares
int switch_2_cases_non_contig(int val) {
    switch(val) {
        case 5:
            return 10;
        
        case 11:
            return 20;
    }

    return 0;
}

// Jump table!
int switch_3_cases(int val) {
    switch(val) {
        case 0:
            return 10;
        
        case 1:
            return 20;

        case 2:
            return 30;
    }

    return 0;
}

// Individual compares
int switch_3_cases_non_contig(int val) {
    switch(val) {
        case 5:
            return 10;
        
        case 11:
            return 20;

        case 17:
            return 30;
    }

    return 0;
}

In most cases, the compiler will only generate a jump table if your switch case labels are contiguous otherwise, it will probably resort to generating separate comparision instructions for each case. Which means that if you have short if-else statements then converting to a switch case may not be necessary. However, if you do have a very long if-else chain that can be converted to a switch case then please do so since it’s more readable.