cpp / beginner
Snippet
Logical Operators: Combining Conditions
Logical operators combine or modify boolean conditions. && (AND) is true only when both operands are true. || (OR) is true when at least one operand is true. ! (NOT) inverts the boolean value. These allow complex decision-making in if statements.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>int main() {int age = 25;bool hasLicense = true;if (age >= 18 && hasLicense) {std::cout << "Can drive legally" << std::endl;}if (!(age < 18)) {std::cout << "Adult" << std::endl;}if (age == 18 || age == 21) {std::cout << "Special age" << std::endl;}return 0;}
Breakdown
1
age >= 18 && hasLicense
AND operator: both conditions must be true
2
!(age < 18)
NOT operator: inverts the result of the condition
3
age == 18 || age == 21
OR operator: true if either condition is true
4
bool hasLicense = true
Boolean type that stores true or false values