C If Else

The C if else statement lets your program make decisions: run one block of code when a condition is true and another when it is false. In C, any non-zero value counts as true and zero counts as false.

The if Statement

#include <stdio.h>

int main(void) {
    int temperature = 32;
    if (temperature > 30) {
        printf("It is hot today.\n");
    }
    return 0;
}
It is hot today.

C if else and else if

Chain conditions with else if. C checks them from top to bottom and runs only the first block whose condition is true.

#include <stdio.h>

int main(void) {
    int score = 74;
    if (score >= 90) {
        printf("Grade A\n");
    } else if (score >= 70) {
        printf("Grade B\n");
    } else if (score >= 50) {
        printf("Grade C\n");
    } else {
        printf("Fail\n");
    }
    return 0;
}
Grade B

The Ternary Operator

condition ? valueIfTrue : valueIfFalse is a short form for choosing between two values.

#include <stdio.h>

int main(void) {
    int n = 7;
    const char *kind = (n % 2 == 0) ? "even" : "odd";
    printf("%d is %s\n", n, kind);
    return 0;
}
7 is odd

Common Mistakes

  • Writing if (x = 5) instead of if (x == 5): the first assigns 5 and is always true.
  • Putting a semicolon after the condition: if (x > 0); makes an empty statement.
  • Leaving out braces and then adding a second line that is not actually inside the if.

Frequently asked questions

What is the difference between if and else if in C?

Separate if statements are each checked independently. else if is only checked when all earlier conditions in the chain were false, so at most one block runs.

Are curly braces required in a C if statement?

Not for a single statement, but using braces every time is strongly recommended because it prevents bugs when you add more lines later.

What counts as true in C?

Any non-zero value is true, and 0 is false. Comparison operators return 1 or 0.