Skip to content

if and else

Read · 1 of 4

Two roads

if (condition) { … } else { … } runs the first block when the condition is true, otherwise the second.

Compare with <, >, <=, >=, == (equal) and != (not equal). Careful: = stores a value, == compares.

In C a condition is just a number: 0 means false, anything else means true.

Read this lesson as text

Run code only when a condition is true.

Two roads

if (condition) { … } else { … } runs the first block when the condition is true, otherwise the second.

Compare with <, >, <=, >=, == (equal) and != (not equal). Careful: = stores a value, == compares.

In C a condition is just a number: 0 means false, anything else means true.

Which branch runs?

#include <stdio.h>

int main() {
    int age;
    scanf("%d", &age);
    if (age >= 18) {
        printf("Can vote\n");
    } else {
        printf("Wait %d more years\n", 18 - age);
    }
    return 0;
}
  1. Line 5: age is 17.
  2. Line 6: Is 17 >= 18? No, so the if block is skipped.
  3. Line 9: The else block runs instead.
  4. Line 11: Either way, the program continues after the if/else.

= or ==?

#include <stdio.h>

int main() {
    int x = 0;
    if (x = 5) {
        printf("yes %d\n", x);
    } else {
        printf("no %d\n", x);
    }
    return 0;
}

What does this print?

  • yes 5
  • no 0
  • no 5
Show the answer

yes 5 x = 5 stores 5 in x, and the value of the whole thing is 5, which isn't 0, so it counts as true. You almost always wanted ==.

Exercise: Even or odd

Read a whole number and print Even or Odd.