C++ Decision Making: If, Else, Else-If Ladders & C++17 Init Statements

Decision-making structures allow a program to evaluate one or more conditions and execute specific blocks of code depending on whether the condition evaluates to true or false.

1. Standard If-Else Statement

#include <iostream>

int main() {
    int marks = 78;

    if (marks >= 90) {
        std::cout << "Grade: A+ (Outstanding)\n";
    } else if (marks >= 75) {
        std::cout << "Grade: A (Distinction)\n";
    } else if (marks >= 50) {
        std::cout << "Grade: B (Pass)\n";
    } else {
        std::cout << "Grade: F (Fail - Try Again)\n";
    }

    return 0;
}

2. Modern C++17 "If with Initializer"

In professional software architecture, limiting variable scope reduces bugs. C++17 introduced local initializers inside the if condition:

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> stock = {{"laptop", 15}, {"phone", 0}};

    // 'item' is created, tested, and destroyed ONLY within this if/else block!
    if (auto item = stock.find("laptop"); item != stock.end() && item->second > 0) {
        std::cout << "Item in stock! Quantity: " << item->second << "\n";
    } else {
        std::cout << "Sorry, out of stock.\n";
    }

    // item is now out of scope - clean and safe!
    return 0;
}
BCA Exam Question:

"What is the Dangling Else problem and how does C++ resolve it?"
Answer: In nested if statements without explicit braces, an else always pairs with the closest preceding unmatched if. Always use explicit curly braces { } to eliminate ambiguity.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is an 'if with initializer' introduced in C++17?

C++17 allows you to declare and initialize a variable directly inside the if statement: 'if (auto it = map.find(key); it != map.end()) { ... }'. The variable 'it' exists ONLY inside the if/else block, preventing scope pollution.

Q2. What is the common bug with the assignment operator (=) inside an if condition?

Writing 'if (x = 5)' instead of 'if (x == 5)' assigns 5 to x, which evaluates as non-zero (true). Modern compilers emit a warning for this, and you can also write Yoda conditions like 'if (5 == x)' to make it impossible to assign accidentally.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ Operators

Review relational and logical operators used in conditions.

C++ Switch Statement

Multi-branch alternative to long if-else ladders.

C++ While Loop

Repeating code blocks based on condition evaluation.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!