Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

The Switch Statement: Discrete Branching

Lesson 12 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

Efficient Multi-Choice Logic

If you are comparing a single variable against many fixed values (like a menu with options 1, 2, 3, 4), a switch statement is much cleaner and often faster than a long else if ladder.

Syntax

switch (variable) {
    case 1:
        // code for option 1
        break;
    case 2:
        // code for option 2
        break;
    default:
        // code if no case matches
}

The Golden Rules of Switch

  1. Integers and Characters ONLY: You can only switch on int, char, or enum. You cannot use float, double, or string.
  2. Constants ONLY: You can only use fixed values in the case. You cannot say case x: (if x is a variable) or case > 10:.
  3. The break is MANDATORY: If you forget the break, C will "fall through" and execute all the code for the following cases too! This is a very common bug.
  4. The default case: This is your safety net. It runs if the variable doesn't match any of your cases.

When to use Switch vs If-Else?

  • Use Switch for a large number of discrete, fixed choices. It's faster because the compiler can use a "Jump Table" to find the right case instantly.
  • Use If-Else for ranges (score > 80), complex logic using && or ||, or when comparing floating-point numbers.

Clever Use: Intentional Fall-Through

Sometimes you want multiple cases to do the same thing.

switch (grade) {
    case 'A':
    case 'B':
    case 'C':
        printf("You passed!\n");
        break;
    case 'F':
        printf("You failed.\n");
        break;
}
Logical fall-through is one of the most common sources of errors in C. Always double-check that every case ends with a break unless you are explicitly trying to group cases together.