Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

labels as values vs. switch statement

Tags:

c

gcc

I read recently about labels as values,

int main(){
    int value  = 2;
    const void *labels[] = {&&val_0, &&val_1, &&val_2};
    goto *labels[value];
    val_0:
        printf("The value is 0\n");
        goto end;
    val_1:
        printf("The value is 1\n");
        goto end;
    val_2:
        printf("The value is 2\n");
        goto end;
    end:
    return(0);
}

what I am asking about is that, is there really any performance gain from using this method instead of using switch statement, or array of pointers?

like image 215
A.M.M Avatar asked Nov 05 '11 11:11

A.M.M


1 Answers

This is a non-standard extension, is likely to perform no better than the equivalent switch statement in this case and is, IMHO, should be avoided. A switch statement is clearer and more maintainable.

(I quickly tested my version of gcc and it produced exactly the same code for both this code and a switch statement equivalent. It wasn't a representative test, though, as it optimized everything out except for the code path actually chosen.)

One potential performance consideration is that the switch statement must have reasonable behaviour even if value isn't in the correct range, your version has undefined behaviour so the compiler may be able to avoid a range check in some code.

like image 176
CB Bailey Avatar answered Nov 12 '22 17:11

CB Bailey