DEV Community

Discussion on: What's the one thing you always need to google?

george profile image
George Nance

Switch statement syntax

cubiclesocial profile image

This probably happens because most people aren't aware of where switch-case came from in the first place. The syntax came about to aid in creating "short jmp" tables in languages like C with intentional fallthrough, which became useful for things like loop unrolling where the performance gains were notable at one point. Loop unrolling was one of the many tricks used to make the first 3D game engines. Nowadays, loop unrolling can have negative side-effects on CPU branch prediction and cause a stall.

Other languages later adopted the style of switch-case but treat it more as a pseudo-if/then/else than something that generates a 'short jmp' table.

Switch-case today still has one very powerful use: State engines (aka Finite State Machines or FSMs/FSAs). Moving from one logical state to another enables powerful functionality that can't be accomplished any other way as efficiently.