C - Conditional Statements
Conditional statements allow your program to make decisions based on boolean expressions.
Learning Objectives
- Use if,if-else, andelse ifladders.
- Choose between ifchains andswitch.
Prerequisites
if / else
#include <stdio.h>
int main(void) {
    int x = 3;
    if (x > 0) {
        printf("positive\n");
    } else {
        printf("non-positive\n");
    }
}
else if ladder
if (score >= 90)      grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else                   grade = 'D';
switch
switch (op) {
  case '+': result = a + b; break;
  case '-': result = a - b; break;
  default:  printf("unknown op\n"); break;
}
Common Pitfalls
- Forgetting breakinswitchcauses fall-through.
- Using assignment =instead of comparison==in conditions.
Checks for Understanding
- When would you prefer switchoverif-else?
- What happens without breakin aswitchcase?
Show answers
- When comparing the same variable to many constant values (e.g., chars, small ints).
- Execution "falls through" into the next case.