r/ProgrammerTIL • u/paddy1709 • Nov 19 '18
C [C] TIL that the switch statement is implemented with goto and that's why you need to explicitly break out of each case
This was leveraged at Lucasfilm in the 80s in early real time animation algorithms. (Link: https://paddyspen.wordpress.com/2018/11/18/bites-of-bytes-ed-8-duffs-device/ )
104
Upvotes
56
u/[deleted] Nov 19 '18
I feel like this isn’t a ‘why’. The two things match nicely sure, and originally the switch was basically sugar for a goto table. The reason now we have fall-through is because it is specified to be like that. If they wanted to specify different semantics they certainly could.
26
u/companiondanger Nov 19 '18
After doing a "write this C program in MIPS" assignment, writing in C felt like I was just using a macro tool to write in assembly. Seeing this just bright that home. Thanks for posting this!
6
u/Marthinwurer Nov 19 '18
It's not always implemented with gotos. I believe some compilers will convert it into basically a big if/else block if it's small enough to take advantage of branch predictors and micro op caches. As always, the only way to really be sure is to check the assembly.