Answer in brief
The switch statement selects a starting point in a multi-way decision by comparing an integer value with case labels.
Syntax
switch (choice) {
case 1:
/* action 1 */
break;
case 2:
/* action 2 */
break;
default:
/* no matching case */
break;
}
Working
- Evaluate the controlling expression once.
- Start at the matching case label. If none matches, start at default when present; otherwise skip the switch.
- Execute statements from that point until break or another transfer leaves the switch, or its end is reached.
Example
In the menu example, choice = 2 starts execution at case 2, so Open is printed. break then leaves the switch. A choice such as 9 reaches default and prints Invalid choice. Character constants can also be case values, for example case '+': in a calculator.
Fall-through and restrictions
Without break, execution continues into the statements following later labels. This is called fall-through. Sometimes several labels intentionally share one action; otherwise, a missing break can be a mistake. Case labels cannot use runtime variables or floating-point values. Ranges such as case 1 to 5 are not standard C syntax. Use if-else for range tests.
Time complexity
C does not require one particular switch implementation. A compiler may use comparisons or a jump table. Do not claim that every switch is always O(1). This small fixed menu does only a fixed amount of work.
C program and output
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int choice = 2;
switch (choice) {
case 1: puts("New"); break;
case 2: puts("Open"); break;
case 3: puts("Save"); break;
default: puts("Invalid choice"); break;
}
return 0;
}
Sample input and output
This example uses values already written in the program.
Output
Open