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

C++ Logical Conditions

Logical operators (&&, ||, !) combine multiple individual conditions into a single expression an if statement can test, using short-circuit evaluation to skip unnecessary checks.

Logical Operators in Conditions

Logical operators combine multiple individual conditions into a single expression that an if statement can test, letting a decision depend on more than one factor at once.

Example: Logical Operators in Conditions

cpp
#include <iostream>

int main() {
	int age = 20;
	bool hasID = true;
	if (age >= 18 && hasID) {
		std::cout << "Allowed" << std::endl;
	}
	return 0;
}

Combining Conditions with &&

The && (logical AND) operator combines two conditions so the overall expression is true only when both individual conditions are true, commonly used to check that a value falls within a specific range.

Example: Combining Conditions with &&

cpp
#include <iostream>

int main() {
	int temperature = 25;
	bool isSunny = true;
	if (temperature > 20 && isSunny) {
		std::cout << "Good weather" << std::endl;
	}
	return 0;
}

Combining Conditions with ||

The || (logical OR) operator combines two conditions so the overall expression is true when at least one of them is true, useful for checking whether a value matches any of several acceptable options.

Example: Combining Conditions with ||

cpp
#include <iostream>

int main() {
	bool hasCash = false;
	bool hasCard = true;
	if (hasCash || hasCard) {
		std::cout << "Can pay" << std::endl;
	}
	return 0;
}

Negating a Condition with !

The ! (logical NOT) operator inverts a single condition, turning a true value false and a false value true, which is often used to read naturally as not in front of a condition's name.

Example: Negating a Condition with !

cpp
#include <iostream>

int main() {
	bool isRaining = false;
	if (!isRaining) {
		std::cout << "Go outside" << std::endl;
	}
	return 0;
}

Short-Circuit Evaluation

C++ evaluates && and || using short-circuit evaluation: for &&, if the first condition is false, the second is never evaluated at all, which is commonly used to safely guard against operations like division by zero.

Example: Short-Circuit Evaluation

cpp
#include <iostream>

bool sideEffect() {
	std::cout << "Second condition evaluated" << std::endl;
	return true;
}

int main() {
	bool first = false;
	if (first && sideEffect()) {
		std::cout << "Both true" << std::endl;
	}
	std::cout << "Done" << 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.