Controlling the Flow
Most programs need to make decisions. "If the user is logged in, show their profile; otherwise, show the login page." C uses if, else, and else if for this.
1. The Simple if
The code block { } only runs if the condition in the parentheses is True (non-zero).
if (balance < 0) {
printf("Warning: Your account is overdrawn!\n");
}
2. The if-else Duo
Provides two mutually exclusive paths. One of them must run.
if (score >= 40) {
printf("Congratulations, you passed!\n");
} else {
printf("I'm sorry, you failed. Keep studying!\n");
}
3. The else if Ladder
Used for more than two choices. C checks them in order, top to bottom. As soon as it finds a true one, it runs it and skips the rest of the ladder.
if (temp > 30) {
printf("It's a hot day.\n");
} else if (temp > 20) {
printf("It's a pleasant day.\n");
} else if (temp > 10) {
printf("It's a bit chilly.\n");
} else {
printf("It's freezing!\n");
}
4. Nested Decisions
You can put an if inside another if.
if (hasAccount) {
if (passwordCorrect) {
printf("Access Granted.\n");
} else {
printf("Wrong password.\n");
}
}
What is "True" in C?
Unlike many languages, early C didn't have a dedicated bool type. Instead:
- 0 is False.
- Any non-zero value (1, -5, 100, 0.5) is True.
if (5) { printf("This always prints!"); }
if (0) { printf("This never prints."); }
The Ternary Operator Shorthand
For very simple decisions, you can use ? :.
int price = (isMember) ? 10 : 20;
This reads: "Is isMember true? If yes, price is 10. If no, price is 20."
The Semicolon Trap: Never put a semicolon immediately after theifparentheses:if(x > 5); { ... }. This tells C theifstatement is finished, so the code in{ }will run every time, regardless ofx!