If you want to do more complex decisions in C++ there are a couple of ways to accomplish this. We’ll look at three that are fairly common.
Nested If Statements
Inside of an if statement true block, or the else block for that matter, you can nest another if statement. This allows you to build more complex logic within your if statements.
if( i > k ) {
if ( j > k ) {
cout << "Both i and j are greater than k." << endl;
}
else
{
cout << "i is greater than k, but j is less than or equal to k."
<< endl;
}
}
Notice how the else statement is contained within the outer if block, that means it is connected to the inner if block. Braces help you identify where an else belongs if necessary.
Else – If Statements
If you had multiple chained if statements in Python, you could use the elif
command. C++ does not have that, however, it does let you chain via the else if. These are actually two separate statements, but act as one as is seen below in our general form.
if (condition 1)
{
// condition 1 true block
}
else if (condition 2)
{
// condition 2 true block
}
This can continue on for a long time in C++. Each condition is independent of the others, so you can test how ever you want. However, once the first true statement if found, no more conditions will be tested.
You may also have an option else block as part of the if-else-if set of statements.
if ( age > 100 )
{
cout << "You've made it. You're officially old." << endl;
}
else if ( age > 65 )
{
cout << "Retirement age, finally." << endl;
}
else if ( age > 21 )
{
cout << "You've become an adult." << endl;
}
else
{
cout << "You're just a kid." << endl;
}
Logical Operators
Sometimes you need nested if statements because of the logic, sometimes you can combine them with logical operators.
Operator | Name |
---|---|
! | Not |
&& | And |
|| | Or |
Both the && and || use short circuit logic. That means if the first condition in the or (||) is true, it doesn’t bother to test the second. Likewise, if the first condition test in the && is false, it doesn’t test the second condition, because they are unnecessary.
if( i > 8 && i < 13 ) {
// there is no between operator, but we can use the &&
// to make one ourselves
}
Advanced Selections in C++ was originally found on Access 2 Learn