Page 1 of 1

Strange switches

Posted: Wed Nov 06, 2002 1:46 am
by sonneveld
Heya,

been looking into compilers and I didn't know that this was legal C:

Code: Select all

switch(a)
     case 0: case 10: case 53: printf("gotcha.\n");
notice the lack of curly brackets? bit annoying to implement since I've done labels slightly differently in my compiler but I thought it would be interesting to use if you needed a variable to be a certain group of values.

- Nick

Re:Strange switches

Posted: Wed Nov 06, 2002 2:17 am
by df
sometimes fallthrough is good.
what about basics implementation of case..

Code: Select all

case 1 to 20 or 31, 32 and 54
  ....
case 22
etc

Re:Strange switches

Posted: Wed Nov 06, 2002 2:39 am
by sonneveld
I think I'll stick with straight contants for now.. but I might look into that later.

One thing I've noticed while disassembling AGI (and further proof they used a compiler of some sorts for parts of it) is their implementation of switch statements.

They always had the switch statement like this (pseudo):

Code: Select all

goto switch;

one:
  code
two: 
  code
three:
  code
default:
  code
goto next;

switch:
if 1 goto one;
if 2 goto two;
if 3 goto three
goto default;

/* jump tables were also used */

next:
I hope that makes sense. the point I'm trying to make is that they always had the statement block first and then the switch jump table

I finally realised the reason why when I started doing my own: single pass compilers.

If you were to put all the switch jumps at the start.. you would have to parse the statements first to look for any case labels, store that in memory somewhere, print out your switch jump table and then the saved statements.

Storing all that data could take a lot of space. And you don't want to have to parse the statments twice because your parser might not allow it.

Alternatively, you could save a bit of space to insert a goto, print out your statement block, and then your switch jump table. once you know where you jump table is, you just have to fill in the proper address at the start via backpatching.

umm. I thought it was interesting.. but kinda hard to explain :)

- Nick

Re:Strange switches

Posted: Wed Nov 06, 2002 6:31 am
by Andrew_Baker
Yar, me matey, then each switch statement is it's own discrete block.

Also, that C format is to support a lot of different things:

case 'a' : case 'A' :

, for example. About the most acceptable kind of fall-through, as well. Almost like overloading...