0 day streak
cpp / intermediate
Snippet

Logic Short-Circuiting in Control Structures

C++ uses short-circuit evaluation for logical AND (&&) and OR (||) operators. If the first operand of an AND is false, the second is not evaluated, which is useful for checking pointers before dereferencing them.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
bool isSecure();
bool hasAccess();
void validateUser() {
if (isSecure() && hasAccess()) {
std::cout << "Access granted" << std::endl;
} else {
// if isSecure() is false, hasAccess() is never even called
std::cout << "Access denied" << std::endl;
}
}
Breakdown
1
if (isSecure() && hasAccess())
The second function 'hasAccess' is only executed if 'isSecure' returns true.