switch and the ? : Operator

switch

When you compare one variable against many exact values, switch is neater than a long else if chain:

#include <stdio.h>

int main() {
    int day;
    scanf("%d", &day);
    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        default:
            printf("Another day\n");
    }
    return 0;
}

Input (what the user types)

2

Output

Tuesday
  • switch (day) looks at the value of day.
  • It jumps to the matching case.
  • break leaves the switch.
  • default runs when no case matches (like else).

Common mistake: Forgetting break. Without it, C keeps going and runs the next cases too! This is called falling through.

Sometimes falling through is useful, to give several cases the same code:

#include <stdio.h>

int main() {
    char c = 'e';
    switch (c) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            printf("%c is a vowel\n", c);
            break;
        default:
            printf("%c is a consonant\n", c);
    }
    return 0;
}

Output

e is a vowel

Tip: switch works with whole numbers and characters, not with decimals or text.

The ? : operator

To pick between two values in one line, use condition ? valueIfTrue : valueIfFalse:

#include <stdio.h>

int main() {
    int a = 8;
    int b = 13;
    int bigger = (a > b) ? a : b;
    printf("Bigger: %d\n", bigger);
    return 0;
}

Output

Bigger: 13

Remember: Use if/else for most decisions, switch for many exact values, and ? : for a quick choice between two values.

HOME LABS COMMUNITY DASHBOARD