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