Introduction

Conditional statements are fundamental in programming languages as they allow programmers to make choices based on the state of the data. In C, there are two primary ways to perform conditional statements: the if statement, accompanied by the else helper, and the switch statement.

if Statement

The if statement allows you to check a condition and execute a block of code enclosed in curly brackets if the condition is true. Here is an example:

int a = 1;

if (a == 1) {
    /* do something */
}

To handle the case when the condition is false, you can add an else block:

int a = 1;

if (a == 2) {
    /* do something */
} else {
    /* do something else */
}

It’s important to use the comparison operator == in comparisons instead of the assignment operator =. Using the assignment operator in the condition will result in the conditional check always being true, except when the argument is 0. For example:

int a = 0;

if (a = 0) {
    /* never invoked */
}

In this case, the condition a = 0 will be true because assignment returns the assigned value, which is 0 in this case.

Multiple else blocks can be achieved by stacking multiple if statements:

int a = 1;

if (a == 2) {
    /* do something */
} else if (a == 1) {
    /* do something else */
} else {
    /* do something else again */
}

switch Statement

The switch statement is useful when multiple if statements are required to check the exact value of a variable. Instead of stacking if statements, the switch statement can provide a more concise solution. Each expected value can be associated with a case entry point:

int a = 1;

switch (a) {
    case 0:
        /* do something */
        break;
    case 1:
        /* do something else */
        break;
    case 2:
        /* do something else */
        break;
}

For each case, we need to include a break statement at the end to prevent the execution of the next case block when the preceding one ends. However, the “cascade” effect can be utilized creatively in certain scenarios.

A “catch-all” case labeled as default can be added at the end to handle all other cases:

int a = 1;

switch (a) {
    case 0:
        /* do something */
        break;
    case 1:
        /* do something else */
        break;
    case 2:
        /* do something else */
        break;
    default:
        /* handle all the other cases */
        break;
}

Tags: C programming, conditionals, if/else, switch