C/C++ Arena

if, else and switch in C

Making decisions in C with if, else if, else and switch, plus the comparison and logical operators.

if runs a block only when its condition is true (any non-zero value). Chain options with else if and finish with else.

Comparisons are ==, !=, <, <=, > and >=. Combine them with && (and), || (or) and ! (not). A classic bug is writing = (assignment) where you meant ==.

switch picks a case by an integer value. Each case needs a break, or execution falls through into the next case.

Example

#include <stdio.h>

int main(void) {
    int score = 72;
    if (score >= 90) {
        printf("A\n");
    } else if (score >= 70) {
        printf("C or better\n");
    } else {
        printf("keep going\n");
    }
    switch (score / 10) {
    case 7:
        printf("seventies\n");
        break;
    default:
        printf("other\n");
    }
    return 0;
}

Output:

C or better
seventies

Practice it