Use enum Types in switch Statements

Use enum Types in switch Statements

Certain compiler and code analyzers can detect a missing enumerator in a switch statement. Consider:

 enum Seasons{ Winter, Spring, Summer, Fall};switch (s){case Winter:  wearCoat();  break;case Spring:  pruneGarden();  break;case Summer:  goSwimming();  break;  // forgot to include a case for 'Fall'}

The programmer listed only three cases in the switch statement, omitting Fall by accident. A clever compiler can catch this omission and warn the programmer that the switch statement misses one of the enumerators. Had we used plain constants rather than an enum type, this omission would have passed unnoticed.


Share the Post: