Nested Conditionals

Sometimes we need to make another decision inside a condition. This is what nested conditionals are for - conditions inside other conditions:

int age = 20;
bool hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        std::cout << "Can drive a car" << std::endl;
    } else {
        std::cout << "Doesn't have a license" << std::endl;
    }
} else {
    std::cout << "Too young to drive" << std::endl;
}

We can use nested conditions at any depth, but with each nesting level the code becomes less readable. Therefore, it's often better to use logical operators:

// Instead of nested conditions
if (age >= 18 && hasLicense) {
    std::cout << "Can drive a car" << std::endl;
} else {
    std::cout << "Cannot drive a car" << std::endl;
}

Instructions

We often try to avoid nesting because it makes code less readable. But it's good to know about this concept, as it can sometimes be simpler to use.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/10

Nested Conditionals | Start Coder