C++ if Statement
In this page:
Basic if Statement
An if statement evaluates a condition and executes its associated block only when that condition is true; when it's false, the block is skipped entirely and execution continues right after it. This is the most fundamental building block for making a program's behavior depend on data rather than always doing the same thing.
Example: Basic if Statement
#include <iostream>
int main() {
int age = 20;
if (age >= 18) {
std::cout << "Adult" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Comparison inside if Condition
Comparison operators like == inside an if condition let you branch based on whether two values match, such as if (userChoice == y). Be careful not to accidentally type a single = here, since that would assign instead of compare and would almost always evaluate to true regardless of the actual values.
Example: Comparison inside if Condition
#include <iostream>
int main() {
char userChoice = 'y';
if (userChoice == 'y') {
std::cout << "Confirmed" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Logical AND in if Conditions
Combining two conditions with && inside an if requires both to be true before the block runs, such as if (age >= 18 && hasLicense), which only grants access when every requirement is satisfied simultaneously. This is how you express 'all of these things must hold' in code.
Example: Logical AND in if Conditions
#include <iostream>
int main() {
int age = 20;
bool hasLicense = true;
if (age >= 18 && hasLicense) {
std::cout << "Can drive" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Logical OR in if Conditions
Using || instead lets the block run if at least one condition is true, such as if (isWeekend || isHoliday), useful whenever any single qualifying condition should be enough to proceed. Mixing && and || in one condition often needs parentheses to make the intended grouping unambiguous.
Example: Logical OR in if Conditions
#include <iostream>
int main() {
bool isWeekend = false;
bool isHoliday = true;
if (isWeekend || isHoliday) {
std::cout << "No work today" << std::endl;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested if Statements
Placing one if inside another lets you check a second condition only once the first has already passed, such as verifying a user is logged in before separately checking whether they have admin rights. This mirrors real decision-making, where some questions only make sense to ask after an earlier one has already been answered.
Example: Nested if Statements
#include <iostream>
int main() {
bool isLoggedIn = true;
bool isAdmin = true;
if (isLoggedIn) {
if (isAdmin) {
std::cout << "Welcome, admin" << std::endl;
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: