There are several uses for the switch statement in C and C++. The two most common uses are for discriminating variant records and for implementing state machines. C++ eliminates the need to use the switch statement for variant records. As the accompanying article points out, using switch to support variant records in C++ is considerably weaker than using polymorphism. But programmers should not get carried away while trying to eliminate all switch statements. Some uses of switch, such as state machines, are still valid. Programs commonly use state machines to implement constructs like parsers and event loops.Consider trying to write a program segment to parse floating-point number strings. Floating-point strings consist of an optional sign character, one or more digit characters, an optional decimal point character and trailing digit characters.
The machine starts in the Initial state. Each input character causes the machine to move to its next state by taking the arc associated with the input character. For example, from the Initial state a digit character (0-9) will place the state machine in the Digit state. A sign character (+ or -) will move the state machine from the Initial state to the Sign state. Any other characters will move the state machine from the Initial state to the Error state. If the state machine enters the Error state, the input was not a valid floating-point string. When the state machine reaches the Final state, the input string is a valid floating-point string. The following code segment implements this state machine:
state = initial_state; while (( state!= final_state) && (state ! =error_state)) { switch (c = getchar()) { case initial_state: if (issign(c)) state = sign_state;xe else if (isdigit(c)) state = digit_state; else state = error_state; break; case sign_state: if (isdigit(c)) state = digit_state; else state = error_state; break; case digit_state: if (isdigit(c)) state = digit_state; else if (ispoint(c)) state = point_state; else state = final_state; break; case point_state: if (isdigit(c)) state = trailing_state; else state = final_state; break; case trailing_state: if (isdigit(c)) state = trailing_state; else state = final_state; break; } }Programmers use switch statements to implement state machines because they are simple to develop and easy to maintain. A good reason to use polymorphism to replace variant record switch statements is to ease maintenance and debug. Programs that try to use polymorphism to replace state machine switch statements are not easier to maintain or debug. By recognizing variant records and state machines, programmers can use the right tool for the right purpose.