The BCPL and C languages implemented switch
(switchon
in BCPL) as a higher-level implementation of an assembly branch table.
A branch table is a very efficient implementation of an if/else chain that uses a single integer to index into an array of addresses (or address offsets). Program control jumps to the address at the specified index of the table.
switch
requires an integer type (or a type implicitly convertible to an integer) because array-indexing requires an integer type.
C++ inherited the same language properties of switch
without making significant changes.
It would be possible to redefine the language to implement switch
using operator ==
, but that same behavior can already be implemented as an if/else chain.