Definition
📌 Conditions
C++ conditional statements work exactly like C's, with the bonus that conditions now naturally evaluate to a real bool instead of just an integer convention..
Syntax
syntax
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}Example
cpp
#include <iostream>
using namespace std;
int main() {
int marks = 72;
if (marks >= 90) {
cout << "Grade: A" << endl;
} else if (marks >= 60) {
cout << "Grade: B" << endl;
} else {
cout << "Grade: C" << endl;
}
return 0;
}Output
outputGrade: B
Important Points
- Use
switchfor many exact-value checks on one variable. - Always add
break;in eachswitchcase to avoid fall-through. - The ternary operator
a > b ? a : bis handy for simple two-way choices. - Braces are optional for single-statement bodies, but recommended for clarity and safety.
Common Mistakes
- Adding a stray semicolon after
if (condition);. - Forgetting
break;insideswitchcases. - Nesting too many
if/elselevels instead of usingswitchor early returns.
Interview Tip
🎯 Before your interview
Be ready to compare
switch vs a chain of if/else if — switch is often faster and cleaner for many discrete values.
