Logical Operators in C++
Logical operators combine conditions: && (and), || (or), and ! (not). Both && and || short-circuit — evaluation stops the moment the result is decided, so in p && q, q never runs when p is false. This is both a performance feature and a safety idiom: ptr && ptr->valid() never dereferences a null pointer.
C++ also offers wordy alternatives (and, or, not) that behave identically. Precedence trips people up: && binds tighter than ||, so a || b && c means a || (b && c) — parentheses remove all doubt.
&&, ||, !
And needs both sides true, or needs at least one, not flips a bool. Results are always bool.
Short-circuit evaluation
&& stops at the first false, || stops at the first true — later operands may never execute, which guards null checks and bounds checks.
Precedence: !, then &&, then ||
!a && b parses as (!a) && b, and a || b && c as a || (b && c). Parenthesize anything non-trivial.
Bool/integer interplay
Any nonzero integer counts as true in a condition, but prefer real bools — implicit int-to-bool conversion hides intent.
#include <iostream> int main() { int age = 20; bool hasId = true; std::cout << (age >= 18 && hasId) << std::endl; std::cout << (age < 18 || !hasId) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.