cerr cerr - 1 month ago 10
C Question

efficient switch statement when using enums

I have an enum and a switch statement using some of the enum entries but not all and they are currently out of order too, i.e. I have the following:

enum prot_tun_stat_e {
STAT_A = 0,
STAT_B,
STAT_C,
STAT_D,
STAT_E,
STAT_F, //5
STAT_G,
STAT_H,
STAT_I,
STAT_Y,
STAT_K, //10
STAT_COUNT //must be last
} __attribute__((packed));


and then I have a switch using the following entries:

switch(var) {
case C:
break;
case D:
break
case F:
break
case G:
break
default
}


and I was wondering if I better rearranged the items in the enum to be
C=1,D=2,F=3&G=4
? Would that be more efficient?

Thanks,
Ron

Platform:
PowerPC
, compiler
diab

Answer

If the compiler can determine that the parameter to the switch statement is limited to a small number then it can create a jump table. This table will take up less room if the values are contiguous but the difference between 4 entries or the 10 required is unlikely to matter. (And note that 0-3 is a better range than 1-4 - although the compiler can deal with this by jumping to offset n - 1).

You can check the output of the compiler to see if a jump table is being created (assuming you can read assembly!). And of course the answer to all performance questions: profile it!