Course contentsShow
← C
Lesson 245 of 1,2194. Control FlowFree lesson

The else clause for alternative paths

The else clause for alternative paths

What you'll learn: How to use the else keyword to provide a guaranteed backup plan when an if condition isn't met.

In our previous lesson, we saw how an if statement acts like a gatekeeper: if the condition is true, you enter; if not, you simply keep walking past. But what if you need to do something different specifically because that first condition failed? In programming, we call this "binary branching"—a fork in the road where you must take exactly one of two paths.

The "Otherwise" Logic

Think of a standard thermostat. You might have a rule that says: "If the temperature is below 65 degrees, turn on the heater." However, if you leave it at that, the heater stays off if it's 66 degrees, but the system doesn't know what to do next. To make a complete system, you need a backup plan: "Otherwise, turn on the fan."

In C, the else clause serves as this "otherwise." It catches every case where the if statement was false. Unlike the if statement, an else does not have its own parentheses or condition because it represents the "everything else" category.

Seeing it in C

When you use an else block, you guarantee that one—and only one—of the two code blocks will run.

#include <stdio.h>

int main() {
    int age = 16;

    if (age >= 18) {
        printf("You are eligible to vote!\n");
    } else {
        printf("You are too young to vote. Try again in a few years.\n");
    }

    return 0;
}

In the example above, the computer checks if age is 18 or older. If that is true, it prints the voting message and completely ignores the else block. However, since 16 is less than 18, the if fails, and the computer jumps straight into the else block.

Why use else?

You could technically write two separate if statements (one for age >= 18 and one for age < 18), but using else is much cleaner and safer. It tells the computer that these two actions are mutually exclusive. It also makes your code faster and easier for other humans to read, as they immediately understand that the program is choosing between two specific alternatives.

Key takeaway

The else clause provides a default action that runs only when the preceding if condition is false.