SyntaxStudy
Sign Up
C if, else, and switch Statements
C Beginner 1 min read

if, else, and switch Statements

The `if` statement is C's primary decision-making construct. It evaluates a condition expression; if the result is non-zero (true), the body executes. An optional `else` branch runs when the condition is zero (false). Multiple conditions can be chained with `else if`. The condition can be any expression — C has no dedicated boolean type in C89, though `` provides `bool`, `true`, and `false` in C99 and later. The `switch` statement compares a single integer expression against a list of constant `case` labels. When a match is found, execution jumps to that label and continues until a `break` statement or the end of the `switch` body. Omitting `break` causes execution to "fall through" to subsequent cases, which is occasionally intentional but usually a bug. A `default` label handles values that match no `case`. Choosing between `if/else if` and `switch` is partly stylistic. `switch` is typically more readable when dispatching on a single variable across many discrete values, especially character codes or enum values. However, `switch` only works with integer and character types — for ranges, floating-point values, or complex boolean conditions, `if/else` is the right tool.
Example
#include <stdio.h>
#include <stdbool.h>   /* bool, true, false (C99) */

const char *day_type(int day)
{
    switch (day) {
        case 1:  /* fall-through intentional */
        case 7:
            return "weekend";
        case 2: case 3: case 4: case 5: case 6:
            return "weekday";
        default:
            return "invalid";
    }
}

int main(void)
{
    /* if / else if / else */
    int temperature = 22;

    if (temperature < 0) {
        printf("Freezing\n");
    } else if (temperature < 10) {
        printf("Cold\n");
    } else if (temperature < 25) {
        printf("Comfortable\n");   /* this branch runs */
    } else {
        printf("Hot\n");
    }

    /* switch with fall-through demonstration */
    for (int d = 1; d <= 7; d++) {
        printf("Day %d is a %s\n", d, day_type(d));
    }

    /* bool type from <stdbool.h> */
    bool is_valid = (temperature >= -50 && temperature <= 60);
    if (is_valid) {
        printf("Temperature %d is within valid range\n", temperature);
    }

    return 0;
}