C: Conditional Statements

🗓 Last updated: 2026-11-30👤 Written by: Ivy✓ Reviewed by: Alex🏷 Category: C Tutorial

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.

Reference entries in this section: if else switch case break int char enum default

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.

C
// 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;
}
TEXT
Excellent!
Program continues
💡 Tip: If there is only one statement after 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.

C
// 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;
}
TEXT
You are a minor

(1) The Dangling else Problem

When multiple if statements are nested, else pairs with the nearest if:

C
// 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:

C
// Conditional check
if (a > 10) {
    // Conditional check
    if (b > 0) {
        // I/O operation
        printf("A\n");
    } else {
        // I/O operation
        printf("B\n");
    }
}
⚠️ Note: Always using braces completely eliminates the dangling else problem.


3. The if-else if-else Chain

When multiple conditions need to be checked in sequence, use else if to chain multiple branches:

C
// 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;
}
TEXT
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.

💡 Tip: Place the most likely conditions first for better efficiency; arrange ranges from largest to smallest to avoid logic gaps.


4. Nested if Statements

An if can be nested inside another if for more refined conditional logic:

C
// 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;
}
TEXT
Adult male
⚠️ Note: Nesting should not exceed 3 levels. Too many levels hurt readability. Complex conditions can be combined with logical operators or flattened using 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

TEXT
switch (expression) {
    case constant1:
        statement;
        break;
    case constant2:
        statement;
        break;
    default:
        statement;
        break;
}
C
// 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;
}
TEXT
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".

C
// 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;
}
TEXT
Two
Three
Default
⚠️ Note: Forgetting 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:

C
// 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;
}
TEXT
Pass

(4) Limitations of switch


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:

C
// 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;
}
TEXT
|-5| = 5
Equal
💡 Tip: The conditional operator can be nested, but readability drops quickly. If nesting exceeds one level, use if-else instead.

▶ Example

Determine body type based on BMI, demonstrating multi-branch conditional logic:

▶ Try it Yourself
TEXT
BMI: 22.9
Normal

▶ Example

Implement a simple menu selection using switch:

▶ Try it Yourself
TEXT
===== Menu =====
1. New Game
2. Continue
3. Settings
4. Exit
================
Your choice: 2
Loading save...

▶ Example 3: switch with break

▶ Try it Yourself

输出:

TEXT
Wednesday

Reference entries in this section: if else switch case break int char enum default

❓ FAQ

Q When can braces be omitted after if?
A Syntactically, braces can be omitted when there is only one statement after if/else, but it is recommended to always use them to avoid bugs from forgetting to add braces when adding more statements later.
Q Can switch evaluate floating-point numbers or strings?
A No. switch only accepts integer expressions. Neither floating-point numbers nor strings work. To compare strings, use an if-else if chain.
Q Can the default branch be omitted?
A Syntactically yes, but it is recommended to keep it to handle unexpected cases and avoid silent errors from missing values.
Q What is the difference between else if and nested if?
A 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

📝 Exercises

  1. Write a program that reads an integer and determines whether it is positive, negative, or zero, then prints the result.
  2. Write a program that reads a month number (1-12) and uses switch to output the number of days in that month (assume a non-leap year, so February has 28 days).
  3. Write a program that reads a character and determines whether it is an uppercase letter, a lowercase letter, a digit, or some other character.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏