capypad
0 day streak
cpp / beginner
Snippet

Boolean Logic with Logical Operators

Logical operators let you combine multiple boolean conditions. && (AND) returns true only if ALL conditions are true. || (OR) returns true if ANY condition is true. ! (NOT) inverts a boolean value. These operators follow precedence rules where ! is evaluated first, then &&, then ||.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
 
int main() {
int age = 25;
bool hasLicense = true;
bool isDrunk = false;
 
// Logical AND - both must be true
bool canDrive = hasLicense && !isDrunk;
std::cout << "Can drive: " << (canDrive ? "Yes" : "No") << std::endl;
 
// Logical OR - at least one must be true
bool canEnter = (age >= 18) || (hasLicense);
std::cout << "Can enter: " << (canEnter ? "Yes" : "No") << std::endl;
 
// Logical NOT - inverts the boolean value
std::cout << "Is drunk: " << (!isDrunk ? "No" : "Yes") << std::endl;
 
// Combining operators with different precedence
bool result = (age > 18 && hasLicense) || (age < 16);
std::cout << "Complex condition: " << (result ? "True" : "False") << std::endl;
 
return 0;
}
Breakdown
1
bool canDrive = hasLicense && !isDrunk;
AND checks both conditions, NOT inverts isDrunk to check if sober
2
bool canEnter = (age >= 18) || (hasLicense);
OR returns true if age is 18+ OR if person has a license
3
std::cout << (!isDrunk ? "No" : "Yes")
NOT operator inverts isDrunk from false to true in output
4
bool result = (age > 18 && hasLicense) || (age < 16);
Parentheses control evaluation order - AND group is checked first