Skip to study material
← Question index

QUESTION 12 · Selection

Explain switch with syntax and a menu-based example.

5 marks

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

  1. Evaluate the controlling expression once.
  2. Start at the matching case label. If none matches, start at default when present; otherwise skip the switch.
  3. 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

Related exam questions

Related questions in the selection category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • March/April 2023 · Q3(a) · 5 marks

    Discuss decision-making statements with an example.

    Paper P02 · page 1
  • June 2022 · Q2(b) · 8 marks

    Illustrate forms of if statements with syntax and examples.

    Paper P03 · page 1

View this category in the exam question bank →