Nested Conditions
A block of code can contain any code, even another if statement. An if inside the block of another if is called a nested condition. It's useful when one question only makes sense after another. At the movies, for example, we first check whether the visitor has a ticket, and only then how old they are:
bool hasTicket = true;
int age = 15;
if (hasTicket) {
if (age >= 18) {
std::cout << "Enjoy the movie" << std::endl;
} else {
std::cout << "Sorry, this movie is for adults only" << std::endl;
}
} else {
std::cout << "Please buy a ticket first" << std::endl;
}This prints:
Sorry, this movie is for adults onlyThe inner if statement runs only when hasTicket is true. Each else belongs to the if whose block ends with the } right before it: the first one to if (age >= 18), the second one to if (hasTicket). The indentation shows this at a glance: the inner blocks are indented by 4 more spaces, 8 in total, and each else is indented as much as its if.
Nested conditions can often be rewritten with && and else if. This code does the same:
bool hasTicket = true;
int age = 15;
if (hasTicket && age >= 18) {
std::cout << "Enjoy the movie" << std::endl;
} else if (hasTicket) {
std::cout << "Sorry, this movie is for adults only" << std::endl;
} else {
std::cout << "Please buy a ticket first" << std::endl;
}The program gets to else if (hasTicket) only when the first condition is false. With a ticket, that means the visitor is under 18. Neither way is wrong: pick the one that's easier to read.
When neither of the two if statements has an else, a single if with && is almost always clearer. These two conditions:
if (hasTicket) {
if (age >= 18) {
std::cout << "Enjoy the movie" << std::endl;
}
}do the same as a single condition with one level of indentation less:
if (hasTicket && age >= 18) {
std::cout << "Enjoy the movie" << std::endl;
}Instructions
- 1
Only people who are at least 10 years old and at the same time at least 140 cm tall may ride the roller coaster. Rewrite the two nested
ifstatements as a singleifstatement that joins both conditions with&&. The program still printsYou can ride the roller coaster. - 2
Give the new
ifstatement anelsebranch that printsYou can't ride the roller coaster yet, and changeageto8. The program printsYou can't ride the roller coaster yet. With nested conditions, you would need two identicalelsebranches, one for eachif.