3 comments

[ 3.9 ms ] story [ 14.6 ms ] thread
C compilers have been optimising switch statements like this since at least the 90s, haven't they?
I'd be surprised if they haven't been doing that since the very beginning -- the first compilers from K&R. This is the reason why switch only works with integral types (and not with any comparable value such as strings): it's intended to be compiled into an efficient table lookup if the range of case values is dense enough.
If you think that's cool, someone will be around shortly to explain how gcc will use SSE opcodes to improve the speed of string handling functions.

"He's honest, but you gotta watch him a little." - Tony (Chico Marx), "A Day at the Races" (1937)

Everyone talks about how close C is to assembly, and that's often true, but here we see how we benefit from how far it can be from assembly as well. The switch-to-jump-table trick is common enough some will claim it's obvious, but it isn't. Not unless you already know it, anyway; for a lot of newbies, the very idea of being able to jump to an address contained in a register is a non-obvious concept.

This is precisely the kind of trivial but non-obvious knowledge that should be encoded into compilers so the rest of us don't have to know it. That's a big reason why we have compilers in the first place.

Here's something that was on Hacker News a little while ago:

http://prog21.dadgum.com/166.html

http://news.ycombinator.com/item?id=5224576

"The Highest-Level Feature of C" is the switch statement