cpp / beginner
Snippet
Logical Operators and Compound Conditions
Logical operators combine boolean values: && (AND) requires both true, || (OR) requires at least one true, ! (NOT) inverts the value. The ternary operator (? :) provides compact conditional assignment based on a condition.
snippet.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 = 20;bool hasLicense = true;bool hasInsurance = true;if (age >= 18 && hasLicense) {std::cout << "Can drive legally" << std::endl;}if (hasLicense && hasInsurance) {std::cout << "Can rent a car" << std::endl;}if (!hasInsurance) {std::cout << "Cannot drive without insurance" << std::endl;}bool canVote = (age >= 18) ? true : false;std::cout << "Can vote: " << (canVote ? "Yes" : "No") << std::endl;return 0;}
Breakdown
1
age >= 18 && hasLicense
AND operator: true only if both conditions are true
2
hasLicense && hasInsurance
Both must be true to enter the if block
3
!hasInsurance
NOT operator: inverts false to true and vice versa
4
(age >= 18) ? true : false
Ternary operator: returns true if age >= 18, else false