Generating code for the switch statement
Steve Summit
stevesu at copper.UUCP
Thu Aug 7 13:00:51 AEST 1986
In article <610 at hropus.UUCP>, ka at hropus.UUCP writes:
> > As I understand it, a switch/case setup compiles exactly the same as
> > if (var == const1) {.....};
> > else if (var == const2) {.....};
> > else {default_action};
> > anyway.
>
> A compiler should be able to do better than that. Generating good code for
> switches is one place where compiler writers can show they know something
> about searching.
>
> Using a branch table will produce faster and smaller code if the cases
> are consecutive integers.
And then there was version 1 of DEC's VAX/VMS C compiler. I have
this image of the people working on the code generator, saying
something like "well, we work for DEC, and we're writing this
compiler for this Vax, and our friends here at DEC gave us this
lovely CASEB instruction, so let's use it!"
Now, the CASEB instruction is basically a microcode
implementation of a branch table. The trouble is, early versions
of VAX11C used it for _a_l_l switch statements, whether the
labels were reasonably dense or not. Woe betide the poor
programmer who wrote something like
switch(x)
{
case 1:
case 10000:
Yup, you got this enormous object file, which took forever to
compile and link, because it had a CASEB instruction with a
ridiculously sparse branch table in it.
By the way, this problem has been fixed. Version 2 of the VMS C
compiler is quite nice, and I have very few complaints with it.
Steve Summit
tektronix!copper!stevesu
More information about the Comp.lang.c
mailing list