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.
#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;
}
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;
}
"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.
Boost your C++ proficiency by studying these closely connected core modules:
Review relational and logical operators used in conditions.
Multi-branch alternative to long if-else ladders.
Repeating code blocks based on condition evaluation.