Language: EN

cpp-condicional-if-else

What is and how to use the IF-ELSE conditional in C++

The if and if-else conditionals are fundamental control structures in C++ that allow making decisions based on boolean evaluations (true or false).

The IF Conditional

The if structure evaluates a boolean expression and executes a block of code only if the expression evaluates to true. The basic syntax of an if conditional in C++ is:

if (condition) {
    // Code to execute if the condition is true
}

Let’s see it with an example:

int number = 10;

if (number > 5) {
    std::cout << "The number is greater than 5" << std::endl;
}

In this example, the condition number > 5 evaluates to true, so the message “The number is greater than 5” is printed to the console.

The IF ELSE Conditional

The if conditional allows adding an else block of alternative code that will execute if the if condition is false. The basic syntax is:

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Let’s see it with an example:

int number = 3;

if (number > 5) {
    std::cout << "The number is greater than 5" << std::endl;
} else {
    std::cout << "The number is not greater than 5" << std::endl;
}

In this case, the condition number > 5 is false, so the block of code inside the else executes, printing “The number is not greater than 5” to the console.

The IF ELSE-IF Conditional

To evaluate multiple conditions, multiple if / else-if / else blocks can be chained. This allows evaluating several conditions in sequence until one of them is true.

if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition1 is false and condition2 is true
} else {
    // Code to execute if all previous conditions are false
}

Nested Conditionals

It is possible to nest multiple if and if-else structures to evaluate more complex conditions.

int number = 0;
if (number > 0) {
    std::cout << "The number is positive." << std::endl;
} else {
    if (number < 0) {
        std::cout << "The number is negative." << std::endl;
    } else {
        std::cout << "The number is zero." << std::endl;
    }
}

Although nesting conditionals can be useful, it also complicates the readability of the code. It is not advisable to overuse them.

Using Logical Operators in Conditionals

To evaluate multiple conditions within a single if, logical operators such as && (logical AND) and || (logical OR) can be used.

For example, the && operator evaluates to true only if both conditions are true.

int number = 10;

if (number > 5 && number < 15) {
    std::cout << "The number is between 5 and 15" << std::endl;
}

While the || operator evaluates to true if at least one of the conditions is true.

int number = 20;

if (number < 5 || number > 15) {
    std::cout << "The number is less than 5 or greater than 15" << std::endl;
}

Practical Examples