C: Conditional Statements
Conditional statements are like traffic lights at an intersection -- when the condition is met, you take one path; otherwise, you take another. Programs gain intelligence through decision-making.
1. The if Statement
if is the most fundamental conditional. When the condition is true (non-zero), the code inside the braces executes; when false (zero), it is skipped.
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int score = 95;
// Conditional check
if (score >= 90) {
// I/O operation
printf("Excellent!\n");
}
// I/O operation
printf("Program continues\n");
// Return result
return 0;
}
Excellent!
Program continues
if, the braces can be omitted. However, it is strongly recommended to always use braces to avoid logic errors when adding statements later and forgetting to add braces.
2. The if-else Statement
if-else provides two branches: if the condition is true, the if block executes; if false, the else block executes. One of the two will always run.
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int age = 16;
// Conditional check
if (age >= 18) {
// I/O operation
printf("You are an adult\n");
} else {
// I/O operation
printf("You are a minor\n");
}
// Return result
return 0;
}
You are a minor
(1) The Dangling else Problem
When multiple if statements are nested, else pairs with the nearest if:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = 5, b = 0;
// Conditional check
if (a > 10)
// Conditional check
if (b > 0)
// I/O operation
printf("A\n");
// Else branch
else
// I/O operation
printf("B\n");
// Return result
return 0;
}
It looks like the else pairs with the first if, but it actually pairs with the second if, so nothing is printed. Adding braces makes the pairing clear:
// Conditional check
if (a > 10) {
// Conditional check
if (b > 0) {
// I/O operation
printf("A\n");
} else {
// I/O operation
printf("B\n");
}
}
3. The if-else if-else Chain
When multiple conditions need to be checked in sequence, use else if to chain multiple branches:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int score = 78;
// Conditional check
if (score >= 90) {
// I/O operation
printf("Grade: A\n");
} else if (score >= 80) {
// I/O operation
printf("Grade: B\n");
} else if (score >= 70) {
// I/O operation
printf("Grade: C\n");
} else if (score >= 60) {
// I/O operation
printf("Grade: D\n");
} else {
// I/O operation
printf("Grade: F\n");
}
// Return result
return 0;
}
Grade: C
else if conditions are evaluated from top to bottom. Once a condition is satisfied, all subsequent branches are skipped. The order of conditions matters.
4. Nested if Statements
An if can be nested inside another if for more refined conditional logic:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int age = 25;
// Variable declaration
char gender = 'M';
// Conditional check
if (age >= 18) {
// Conditional check
if (gender == 'M') {
// I/O operation
printf("Adult male\n");
} else {
// I/O operation
printf("Adult female\n");
}
} else {
// I/O operation
printf("Minor\n");
}
// Return result
return 0;
}
Adult male
else if.
5. The switch-case Statement
switch jumps to a matching case branch based on the value of an integer expression. It is ideal for branching on discrete values.
(1) Basic Syntax
switch (expression) {
case constant1:
statement;
break;
case constant2:
statement;
break;
default:
statement;
break;
}
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int day = 3;
// Switch statement
switch (day) {
// Case branch
case 1: printf("Monday\n"); break;
// Case branch
case 2: printf("Tuesday\n"); break;
// Case branch
case 3: printf("Wednesday\n"); break;
// Case branch
case 4: printf("Thursday\n"); break;
// Case branch
case 5: printf("Friday\n"); break;
// Case branch
case 6: printf("Saturday\n"); break;
// Case branch
case 7: printf("Sunday\n"); break;
default: printf("Invalid day\n"); break;
}
// Return result
return 0;
}
Wednesday
(2) The Importance of break
After switch matches a case, it executes all statements from that point onward until it encounters a break or the end of the switch. This is called "fall-through".
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int num = 2;
// Switch statement
switch (num) {
// Case branch
case 1: printf("One\n");
// Case branch
case 2: printf("Two\n");
// Case branch
case 3: printf("Three\n");
default: printf("Default\n");
}
// Return result
return 0;
}
Two
Three
Default
break is the most common switch mistake. Unless intentionally using fall-through, always add break at the end of each case.
(3) Using Fall-through to Merge Branches
Sometimes multiple case labels need to execute the same logic. You can deliberately omit break:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
char grade = 'B';
// Switch statement
switch (grade) {
// Case branch
case 'A':
// Case branch
case 'B':
// Case branch
case 'C':
// I/O operation
printf("Pass\n"); break;
// Case branch
case 'D':
// I/O operation
printf("Retake\n"); break;
// Case branch
case 'F':
// I/O operation
printf("Fail\n"); break;
default:
// I/O operation
printf("Invalid grade\n"); break;
}
// Return result
return 0;
}
Pass
(4) Limitations of switch
- The expression must be an integer type (
int,char,enum, etc.); floating-point numbers and strings are not allowed - The value after
casemust be a compile-time constant, not a variable casevalues must not be duplicated
6. The Conditional Operator (Ternary)
The conditional operator ?: can replace simple if-else statements. It was introduced in lesson 6; here are more usage examples:
// Preprocessor directive
#include <stdio.h>
// Function definition
int main(void) {
// Variable declaration
int a = -5;
// Variable declaration
int abs_a = a >= 0 ? a : -a;
// I/O operation
printf("|%d| = %d\n", a, abs_a);
// Variable declaration
int x = 10, y = 10;
// I/O operation
printf("%s\n", x == y ? "Equal" : "Not equal");
// Return result
return 0;
}
|-5| = 5
Equal
if-else instead.
▶ Example
Determine body type based on BMI, demonstrating multi-branch conditional logic:
▶ Try it YourselfBMI: 22.9
Normal
▶ Example
Implement a simple menu selection using switch:
===== Menu =====
1. New Game
2. Continue
3. Settings
4. Exit
================
Your choice: 2
Loading save...
▶ Example 3: switch with break
▶ Try it Yourself输出:
TEXTWednesday
❓ FAQ
if?if/else, but it is recommended to always use them to avoid bugs from forgetting to add braces when adding more statements later.switch evaluate floating-point numbers or strings?switch only accepts integer expressions. Neither floating-point numbers nor strings work. To compare strings, use an if-else if chain.default branch be omitted?else if and nested if?else if is a flat multi-branch structure that is easier to read; nested if is hierarchical and suitable when conditions depend on each other. They are interchangeable -- choose whichever is more readable.📖 Summary
ifhandles single conditions,if-elsechooses between two, andelse ifchooses among multiple branches- Always use braces to avoid dangling else issues and future maintenance problems
switchis ideal for branching on discrete integer values; do not forgetbreakfor eachcase- Fall-through in
switchcan merge branches, but forgettingbreakis a common bug source - The ternary operator
?:is suitable for simple two-way choices; useif-elsefor complex logic
📝 Exercises
- Write a program that reads an integer and determines whether it is positive, negative, or zero, then prints the result.
- Write a program that reads a month number (1-12) and uses
switchto output the number of days in that month (assume a non-leap year, so February has 28 days). - Write a program that reads a character and determines whether it is an uppercase letter, a lowercase letter, a digit, or some other character.