C TutorialLesson 14Free preview
C Switch
This lesson is part of C · All levels
Summary
A switch is an efficient branching structure for comparing one value against many constant choices such as characters or numbers. Every possibility is written in a case, and break prevents the execution from penetrating the next case (fall-through). Default is used as the last branch when there is no case that matches. The switch is best used when the branch selection is clear and based on the same value.
Key points
- The value on the switch is evaluated once and then matched to each case.
- Break is mandatory at the end of each case so that control does not fall on the next case
- Default acts as a catcher when there is no case to match
- The switch only works with the integral type and char, not the string.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.