Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 135 ยท Control Flow

if, else if and else

Learn C's if, else if and else: how conditions are tested, ordering else-if chains, nesting, the dangling else, = vs == bugs, empty bodies and guard clauses.

So far, every program in this course has run from the first line of main to the last, in order. Real programs need to make choices: reject a password that's too short, charge shipping only below a certain order total, print "1 file" but "2 files". The if statement is how C makes a decision, and together with else and else if it's the most used control structure in the language.

The idea is simple, but C's version has a few sharp edges that cause real bugs, some of them famous. In this lesson you'll learn the syntax, how to order a chain of conditions, how else pairs up with if, and how to avoid the = versus == mistake, stray semicolons and missing braces.

The if statement

An if statement evaluates a condition in parentheses. If the condition is nonzero (true), the statement or block after it runs; if it's zero (false), it's skipped:

C
if (condition) {
    // runs only when condition is nonzero
}

The condition can be any scalar expression: a comparison, a logical combination (see Comparison and Logical Operators), a plain integer, or a pointer. That means if (count) is a shorter way to write if (count != 0), and if (ptr) means if (ptr != NULL). Both forms are common; use the explicit one when it makes the meaning clearer.

Add an else branch for the case where the condition is false. Exactly one of the two blocks runs:

C if and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Change the number in the Input box and run it again. The example also checks the return value of scanf: it returns how many values it converted, so anything other than 1 means the input wasn't a number (see Reading Input with scanf and fgets).

Always use braces

C lets you leave out the braces when the body is a single statement:

C
if (temperature > 30)
    printf("Hot!\n");

It's legal, but it's a trap. When someone later adds a second line at the same indentation, it looks like part of the if, but only the first statement is. Indentation means nothing to the compiler. This is how a famous security bug in Apple's SSL code (2014) happened: a duplicated goto fail; line sat under an if without braces, so the second copy always ran and skipped the certificate check.

C Indentation does not make a block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

This example compiles with a warning on purpose. The first "Drink plenty of water." line prints even though it's 12 degrees. GCC flags the trap with a warning, this 'if' clause does not guard... [-Wmisleading-indentation], which is part of -Wall. This course uses braces on every if, else and loop body, as most style guides require.

else if chains

To choose between more than two options, chain conditions with else if. C tests them from top to bottom and runs the first branch whose condition is true; the rest are skipped. A final else catches everything that matched nothing.

C
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else if (score >= 70) {
    grade = 'C';
} else {
    grade = 'F';
}

else if isn't a separate keyword: it's an else whose single statement happens to be another if. Writing it on one line is just a formatting convention that keeps long chains flat.

Because only the first match runs, order matters. Put the most specific or most restrictive conditions first. If the chain above started with score >= 70, a score of 95 would get a C.

C An else-if chain for shipping costs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The loop reads numbers until scanf fails or the input ends; you'll learn loops properly in while and do-while Loops. Comparing cost == 0.0 is safe here because 0.0 is assigned exactly, not computed; for computed floating-point values, use a tolerance.

Nesting and the dangling else

An if can contain another if. That's fine for a level or two, but there's an ambiguity when braces are missing: which if does an else belong to?

C
if (logged_in)
    if (is_admin)
        printf("Admin panel\n");
else
    printf("Please log in\n");     // which if is this for?

The rule: an else belongs to the nearest preceding if that doesn't already have an else. Here that's if (is_admin), despite the indentation, so a logged-in non-admin is told to log in, and a logged-out user sees nothing. This is the dangling else problem. GCC warns: suggest explicit braces to avoid ambiguous 'else'. Braces make the intent unmistakable:

C
if (logged_in) {
    if (is_admin) {
        printf("Admin panel\n");
    }
} else {
    printf("Please log in\n");
}

Deep nesting is hard to read even with braces. Two techniques flatten it:

  • Combine conditions with && when the inner if has no else: if (logged_in && is_admin).
  • Return early. Handle the error or special case first and leave the function; the main logic then runs at the top level of the function. These early exits are called guard clauses.
C Guard clauses instead of deep nesting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Each check is independent, the "happy path" is the last line, and nothing is nested more than one level. strlen and strchr come from <string.h> and are covered in String Functions.

= versus ==

This is the bug every C programmer writes at least once:

C
if (attempts = 3) {        // assigns 3, then tests 3: always true
    lock_account();
}

Assignment is an expression in C (see Assignment and Increment Operators), so attempts = 3 is a valid condition. It stores 3 and then tests 3, which is nonzero, so the branch always runs, and attempts has been overwritten. if (x = 0) is the mirror image: it never runs.

Your defenses:

  1. Compile with -Wall. GCC reports suggest parentheses around assignment used as truth value. Never ignore this warning.
  2. When you really mean assign-and-test, show it with an explicit comparison: if ((file = fopen(name, "r")) != NULL).
  3. Some programmers write constants first, if (3 == attempts), the so-called Yoda condition, because 3 = attempts doesn't compile. With compiler warnings on, it's unnecessary, and most people find it harder to read.

The stray semicolon

A semicolon right after the condition is an empty statement, and it becomes the whole body of the if:

C
if (balance < 0);          // the if controls this empty statement
{
    printf("Overdrawn!\n"); // always runs: it's just a block after the if
}

-Wextra warns suggest braces around empty body in an 'if' statement. Train your eye to never put ; directly after if (...), while (...) or for (...).

if versus the conditional operator

When both branches just pick a value, the conditional operator is shorter and keeps the variable assignment in one place:

C
int larger = a > b ? a : b;
printf("%d item%s\n", n, n == 1 ? "" : "s");

When the branches do things (print, call functions, change several variables), use if. The Operator Precedence lesson covers ?: in detail, and when you're comparing one value against many fixed constants, a switch statement can be clearer than a long else if chain.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With int score = 85;, what does this print? if (score >= 70) { puts("C"); } else if (score >= 80) { puts("B"); } else { puts("F"); }

    The chain runs only the first branch whose condition is true. 85 >= 70 is true, so C is printed and the other conditions are never tested. Put the stricter test first.
  2. 2. With int x = 0;, what happens in if (x = 5) { puts("yes"); }?

    x = 5 is an assignment expression with the value 5, which is nonzero. GCC warns: suggest parentheses around assignment used as truth value.
  3. 3. In if (a) if (b) puts("1"); else puts("2");, which if does the else belong to?

    An else pairs with the nearest preceding if that has no else yet. Use braces to make a different pairing explicit.
  4. 4. With int n = 4;, what does this print? if (n > 10); { puts("big"); } puts("done");

    The semicolon after the condition is an empty statement that forms the if body. The block that follows is an ordinary block and always runs.

Summary

  • if (condition) runs its body when the condition is nonzero; else runs when it's zero. Any scalar works as a condition: if (count) and if (ptr) are common shorthands.
  • Always use braces. Indentation doesn't create blocks, and -Wmisleading-indentation warns when it looks like it does.
  • An else if chain runs only the first true branch, so order conditions from most to least specific, and end with else for everything else.
  • An else pairs with the nearest unmatched if (the dangling else). Braces, combined conditions and guard clauses keep nesting shallow.
  • if (x = 5) assigns instead of compares; heed GCC's warning. A ; right after if (...) makes an empty body.
  • Use ?: to choose between two values and if to choose between two actions.

Next: switch Statements