Lesson 1 of 6 · Control Flow · 2 min read · Updated

Making decisions with if

Run some code only when a condition holds — and the one-character typo that breaks it.

Until now every program ran top to bottom, every line, every time. if is how a program chooses.

c
#include <stdio.h>

int main(void)
{
    int marks;

    printf("Marks out of 100: ");
    scanf("%d", &marks);

    if (marks >= 90) {
        printf("Distinction\n");
    } else if (marks >= 50) {
        printf("Pass\n");
    } else {
        printf("Try again\n");
    }

    return 0;
}
Output
Marks out of 100: 72
Pass

Comparison operators

c
a == b   equal to
a != b   not equal to
a <  b   less than
a <= b   less than or equal to
a >  b   greater than
a >= b   greater than or equal to

Warning

= assigns, == compares. Writing if (x = 5) sets x to 5 and is always true — a bug that compiles cleanly and has cost people entire afternoons. Many compilers warn about it, which is one more reason to read warnings.

Combining conditions

c
if (age >= 18 && has_id) {
    printf("Allowed\n");
}

if (day == 0 || day == 6) {
    printf("Weekend\n");
}

if (!found) {
    printf("Not found\n");
}
  • && — and. Both sides must be true.
  • || — or. Either side will do.
  • ! — not. Flips true to false.

Note

C has no separate true/false type in its older standards. Zero is false; anything else is true. That is why if (count) means "if count is not zero".

What does if (x = 5) do?

Create a free account to save your progress, or sign in.