Choosing from Multiple Options in the C Language with ELSE-IF

By Dan Gookin

The C language gives you a number of ways to build a program that makes a decision. If you need something to happen only when a particular prerequisite is met, C offers you the if keyword. If your program needs to choose from two paths, using else with your if statement gives you even more choices.

If your C program needs to make a more complicated decision, you can use else if. By using else if, you can have several if statements piled on top of each other, narrowing a complex decision tree into a few possible outcomes:

#include <stdio.h>
int main()
    float temp;
    printf("What is the temperature outside?");
    if(temp < 65)
        printf("My but it's a bit chilly out!n");
    else if(temp >= 80)
        printf("My but it's hot out!");
        printf("My how pleasant!");

This is one way to handle multiple conditions in C. Here’s how it works:

  1. The first comparison is made by if in Line 9.

    If the value of the variable temp is less than 65, those statements belonging to if are executed; the rest of the construction (Lines 13 through 20) is skipped.

  2. When the first comparison is false, the comparison is made by else if in Line 13.

    When that comparison is true, the statements belonging to else if are executed; Lines 17 through 20 (inclusive) are skipped.

  3. Finally, when both if and else if comparisons are false, the statements belonging to else (Line 17) are executed.

When you’re performing multiple comparisons, it’s important to get the order right. Often, this requires a visual image, like the one shown here, because, if you cannot visualize the comparisons and the way they eliminate the outcome, the program doesn’t do what you intended. (This is a “bug” type of error.)

How if, else if, and else narrow the possibilities.

How if, else if, and else narrow the possibilities.

In this illustration, you can see how the first if statement eliminates any temperatures lower than 65. Next, the else if statement eliminates all temperatures 80 and higher. When you get to the final else, the temperatures that remain are in the range of 65 to 79.99.

Now assume that someone wasn’t thinking and the three statements appear as shown in the figure that follows. In this example, nothing is left for else to represent, and the program most likely yields an improper answer. (Note that the compiler doesn’t point out this type of mental error.)

Your comparisons can yield bad results if you haven't thought them through completely.

Your comparisons can yield bad results if you haven’t thought them through completely.