GCC "switch" - When does GCC create a jumptable ?

Status
Not open for further replies.

Frank B

Senior Member
Hi,

I have a big switch () {..}:

unsigned i;
....
switch(i) {
case 0: ...break;
case 1: ...break;
...
case 63: ...break;
}

64 cases, no default, no holes. I thought, GCC creates a jumptable, but it does not.
Which criteria must be met ?
Is there a way to force it ?

I'm using -O3 with LTO.
 
Last edited:
It usually does. Maybe your code has a fair amount of overlap and GCC merges those parts. You can try using O1 / O2 / Os - that may change code generation.

You can create a jump table manually with computed gotos. It's a GCC extension, not standard C or C++. It's mostly supported by Clang as well.
 
Yes, there is some overlapping.
The "&&" is new to me - Thank you :)
The other way would have been to create (nearly) 64 functions and an array with functionpointers.
 
There are various knobs that the backend can control to influence how switch tables or if-statements are generated. I don't know what decisions the arm maintainers have made for this. On the PowerPC, we tend to prefer more if/then/elses than a table jump for small numbers of case entries, due to the way the PowerPC handles indirect jumps.

There is a parameter that you can control via command line that biases the decision, and an option to enable/disable jump tables if the table is dense enough:
  • --param case-values-threshold=<n>: The smallest number of different values for which it is best to use a jump-table instead of a tree of conditional branches, if 0, use the default for the machine.
  • -fjump-table: Use jump tables for sufficiently large switch statements.
  • -fno-jump-table: Do not use jump tables for sufficiently large switch statements.
 
Last edited:
Status
Not open for further replies.
Back
Top