Handmade Hero » Forums » Code » Interesting article on switch statements
andrewjdr
AndrewJDR
21 posts
#27 Interesting article on switch statements
4 years, 7 months ago

I found this article about switch statements pretty interesting:

http://741mhz.com/switch/

The author goes into detail about how the C switch statement ends up as assembly on a couple of implementations (Clang and GCC) and a variety of situations (e.g. Different numbers of cases, continuous values vs. sparse values, default case vs. non-default case).
Uberstedt
Johan Öfverstedt
46 posts
#57 Interesting article on switch statements
4 years, 6 months ago

Very interesting article. Goes to show that you should never just assume that your mental model of how your code will be translated to assembly/machine code is correct.
nxsy
Neil Blakey-Milner
46 posts
#59 Interesting article on switch statements
4 years, 6 months ago

Totally tangentially, one of the features that I enjoy in D (the programming language) is "final switch" - http://dlang.org/statement.html#FinalSwitchStatement

When used with D's enumerated type, all possible values must exist as case statements, and no default case is allowed. That way if you extend an enumerated type with a new value, whenever you have used "final switch", the compiler will tell you where you need to handle this value.

Linux XCB platform layer: https://github.com/nxsy/xcb_handmade

Android NDK platform layer: https://github.com/nxsy/ndk_handmade
cmuratori
Casey Muratori
818 posts / 1 project

Casey Muratori is a programmer at Molly Rocket on the game 1935 and is the host of the educational programming series Handmade Hero.

#63 Interesting article on switch statements
4 years, 6 months ago

As a sidenote, compilers like LLVM also allow you do to this - if you use an enum for the switch, and omit a default case, it will warn you if not all enum values are handled.

- Casey