Page Content

Tutorials

What Are Conditional Statements In C++ With Code Examples?

Conditional statements in C++

Conditional statements are an essential component of the flow of control in C++. Depending on whether a given condition evaluates to true or false, they allow a program to change its execution route. For this, C++ offers the conditional operator?:, switch statement, if statement, and if else statement.

Simple if statement

When a certain condition is met, the if statement executes a statement or block of statements. This is known as conditional execution. The statement or statements are skipped and the computer moves on to the code that comes just after the if block if the condition is false.

Syntax (simple if)

if (condition)
    statement; // or a code block { ... }

Condition: The condition must be an expression or declaration of an initialised variable that can be changed to a bool type, and it must be surrounded by brackets (). A value of 0 (zero) in C++ becomes false, while any other non-zero value becomes true.

Code Example (if statement):

#include <iostream> // For input/output operations
int main() {
    int score = 85;
    // A simple if statement to check if the score is passing
    if (score >= 60) { // Condition: score is greater than or equal to 60
        std::cout << "Congratulations! You passed the exam." << std::endl; 
    }
    std::cout << "Your score is: " << score << std::endl;
    return 0;
}

Output

Congratulations! You passed the exam.
Your score is: 85

In this instance, the criterion score >= 60 is true because score (85) is >= 60, and the message “Congratulations! It reads, “You passed the exam.”

A variable can also be declared inside the condition of an if statement, but its scope will be restricted to the blocks of the if statement.

if else statement

Two different statement sequences can be selected using the if else statement. The if block’s statements are carried out if the condition is true. The else block’s statements are carried out in its place if the condition is false. In every case, one of the two blocks will run.

Syntax:

if (condition)
    statement1; // or a code block { ... }
else
    statement2; // or a code block { ... } 

Code Example (if…else statement):

#include <iostream> // For input/output operations
int main() {
    int temperature = 25;
    // An if...else statement to decide on an activity based on temperature
    if (temperature > 30) {
        std::cout << "It's too hot! Let's go swimming." << std::endl;
    } else { // This block executes if temperature is 30 or less
        std::cout << "The weather is nice. Let's go for a walk." << std::endl;
    }
    return 0;
}

Output

The weather is nice. Let's go for a walk.

In this case, the else block is executed since temperature (25) is not more than 30.

else if statement

To handle several conditions and select one alternative from a range of options, the else if construction is utilised. The order in which conditions appear is used for evaluation. The matching block of statements is executed and the remainder of the else if chain is omitted if an if or else if condition evaluates to true. It is optional to insert a final else statement that will run if none of the if or else if criteria listed above are satisfied.

Syntax:

if (condition1)
    statement1
else if (condition2)
    statement2
// ... (any number of else if blocks)
else if (conditionN)
    statementN
else // Optional default statement
    statement_default;

Example of Code (else if):

#include <iostream> // For input/output operations
int main() {
    int hour_of_day = 14; // 2 PM
    // else if chain to determine the time of day
    if (hour_of_day < 12) {
        std::cout << "Good morning!" << std::endl;
    } else if (hour_of_day < 18) { // This condition (14 < 18) is true
        std::cout << "Good afternoon!" << std::endl;
    } else if (hour_of_day < 22) {
        std::cout << "Good evening!" << std::endl;
    } else {
        std::cout << "Good night!" << std::endl;
    }
    return 0;
}

Output

Good afternoon!

The first criterion (hour_of_day < 12) is false in this case since hour_of_day is 14, but the second condition (hour_of_day < 18) is true, hence “Good afternoon!” is printed.

You can also read Expressions in C++: How Code Calculates Values

Nested if Statements and “Dangling else”

It is possible to nest if statements inside of each other. The “dangling else,” which occurs when there are more if branches than other branches, is a frequent issue with nested if statements. In C++, the closest preceding unmatched if is always paired with an else. To avoid this uncertainty, programmers can explicitly create code blocks and control which if an else belongs to by using curly brackets {}.

Conditional Operator ()

The ternary operator, sometimes referred to as the conditional operator,?:, offers a succinct method of incorporating basic if-else logic straight into an expression. When a variable is given one value if a condition is true and another value if it is false, it is especially helpful.

Syntax:

Condition ? expression_if_true : expression_if_false;

First, the condition is assessed. Expression_if_true is evaluated if it is true, and the result is the expression’s total value. Expression_if_false is evaluated and its value is the outcome if it is false. Of the two expressions, only one is ever evaluated. Although it is lower than most other operators, the conditional operator has a greater precedence than assignment operators.

Code Example:

#include <iostream> // For input/output operations
#include <string>   // For string type
int main() {
    int score = 55;
    // Use conditional operator to assign a pass/fail status
    std::string status = (score >= 60) ? "Pass" : "Fail"; // Condition is false, "Fail" is assigned 
    std::cout << "The student's status is: " << status << std::endl;
    int num1 = 15;
    int num2 = 7;
    // Use conditional operator to find the maximum of two numbers 
    int max_value = (num1 > num2) ? num1 : num2; // Condition is true, num1 (15) is assigned
    std::cout << "The maximum value is: " << max_value << std::endl;
    return 0;
}

Output

The student's status is: Fail
The maximum value is: 15

switch statement

Depending on a condition, a switch statement offers a multi-branching mechanism. When checking a single expression against a list of constant values, it is frequently more understandable than a sequence of if else if expressions.

Syntax:

switch (expression) {
    case constant1:
        statement(s);
        break; // Optional 
    case constant2:
        statement(s);
        break;
    // ... any number of case statements
    default: // Optional
        statement(s);
        // break; (often not needed if default is the last case)
}

Expression and Case Labels: The switch statement’s evaluated expression needs to be of the enumerated or integral type. No two case labels in the same switch statement can have the same value; each case label must be an integral constant expression. Characters can be used as case objects since character kinds are regarded as integral.

Execution Flow (“Fall-through”): Execution starts at a case label if the switch expression matches that label. After then, execution proceeds step-by-step through any more case blocks until either the switch statement’s end or a break statement is encountered. Unintentional “fall-through” behaviour occurs when a break statement is overlooked. It is best practice to provide a note describing purposeful fall-through.

default Label: In the event that no case label corresponds to the value of the switch expression, the optional default label specifies the statements that will be performed. Although it is typically near the conclusion of the switch statement, it can be anywhere. Define an empty default section to show that the situation was taken into consideration, even if no specific action is required. In order to handle unexpected inputs, it is usually a good idea to include a default statement.

An example of code (a switch statement)

#include <iostream> // For input/output operations
int main() {
    char command = 's'; // User input for command
    // Switch statement to handle different commands
    switch (command) {
        case 'h':
            std::cout << "Displaying help." << std::endl;
            break; // Exits the switch 
        case 's':
        case 'S': // Both 's' and 'S' fall through to the same action due to no break after 's'
            std::cout << "Saving the current document." << std::endl;
            break;
        case 'o':
            std::cout << "Opening a new document." << std::endl;
            break;
        default:
            std::cout << "Invalid command. Press 'h' for help." << std::endl; 
            // No break needed here as it's the last statement in the switch
    }
    return 0;
}

Output

Saving the current document.

The command in this instance is’s’. The switch terminates because it matches case’s’, executes the statement, and then, because there is no break statement, falls through to case ‘S’.

switch vs. if else

A switch statement can only test a single integral or enumerated expression against a set of constant values, whereas an otherwise if chain can handle any condition, including complex expressions and comparisons involving unrelated variables. Nevertheless, when these requirements are satisfied, the switch statement is frequently easier to read and can result in more effective code production (for example, by using jump tables).

You can also read What Are The C++ Operators And Operator Overloading?

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index