← Back to C++ Course | Chapter 4: Control Flow | Lesson 6 of 13

C++ Nested Conditions

A nested condition is an if statement placed inside another if statement's block, so the inner check only runs once the outer condition has already been satisfied.

What is a Nested Condition?

A nested condition is an if statement placed inside the body of another if statement, and the inner condition is only evaluated at all once the outer condition has already been satisfied.

Example: What is a Nested Condition?

cpp
#include <iostream>

int main() {
	bool outer = true;
	if (outer) {
		bool inner = true;
		if (inner) {
			std::cout << "Inner reached" << std::endl;
		}
	}
	return 0;
}

Basic Nested if

In a basic nested if, the outer if statement's block contains a complete inner if statement, so reaching the innermost code requires every enclosing condition to be true.

Example: Basic Nested if

cpp
#include <iostream>

int main() {
	int age = 25;
	bool hasTicket = true;
	if (age >= 18) {
		if (hasTicket) {
			std::cout << "Entry allowed" << std::endl;
		}
	}
	return 0;
}

Nested if-else

An else branch can itself contain a complete if-else statement, letting nested conditions distinguish between more than two outcomes, such as separating three different age categories.

Example: Nested if-else

cpp
#include <iostream>

int main() {
	int score = 75;
	if (score >= 90) {
		std::cout << "A" << std::endl;
	} else {
		if (score >= 70) {
			std::cout << "B" << std::endl;
		} else {
			std::cout << "C" << std::endl;
		}
	}
	return 0;
}

Multiple Levels of Nesting

Conditions can be nested several levels deep to check increasingly specific combinations of criteria, though very deep nesting tends to make code significantly harder to read and maintain.

Example: Multiple Levels of Nesting

cpp
#include <iostream>

int main() {
	bool loggedIn = true;
	bool isAdmin = true;
	bool hasPermission = true;
	if (loggedIn) {
		if (isAdmin) {
			if (hasPermission) {
				std::cout << "Access granted" << std::endl;
			}
		}
	}
	return 0;
}

Nested Conditions vs Logical Operators

A nested if achieves the same result as combining conditions with the logical AND operator (&&) in a single if statement, and the logical-operator version is often considered more concise and readable for simple combined checks.

Example: Nested Conditions vs Logical Operators

cpp
#include <iostream>

int main() {
	int age = 25;
	bool hasTicket = true;

	if (age >= 18) {
		if (hasTicket) {
			std::cout << "Nested: allowed" << std::endl;
		}
	}

	if (age >= 18 && hasTicket) {
		std::cout << "Logical AND: allowed" << std::endl;
	}
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.