Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!clyde!caip!sri-spam!parcvax!hplabs!tektronix!teklds!copper!stevesu From: stevesu@copper.UUCP (Steve Summit) Newsgroups: net.lang.c Subject: Re: Generating code for the switch statement Message-ID: <526@copper.UUCP> Date: Wed, 6-Aug-86 23:00:51 EDT Article-I.D.: copper.526 Posted: Wed Aug 6 23:00:51 1986 Date-Received: Sat, 9-Aug-86 04:27:07 EDT References: <15093@ucbvax.BERKELEY.EDU> <2765@brl-smoke.ARPA> <610@hropus.UUCP> Organization: Tektronix, Inc., Beaverton, OR Lines: 40 Summary: it can be done badly, too... In article <610@hropus.UUCP>, ka@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