cpp / beginner
Snippet
Logical Operators: Combining Boolean Conditions
C++ provides three logical operators: AND (&&), OR (||), and NOT (!). The AND operator returns true only if both operands are true. The OR operator returns true if at least one operand is true. The NOT operator negates a boolean value, turning true to false and vice versa. These operators allow you to combine multiple conditions in if statements to make complex decisions.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>int main() {int age = 25;bool hasLicense = true;bool hasInsurance = false;if (age >= 18 && hasLicense) {std::cout << "Can drive legally" << std::endl;}if (!hasInsurance) {std::cout << "Need to get insurance" << std::endl;}if (age < 18 || hasLicense == false) {std::cout << "Cannot drive legally" << std::endl;}return 0;}
Breakdown
1
int age = 25;
Integer variable storing an age value
2
bool hasLicense = true;
Boolean true indicating possession of a license
3
bool hasInsurance = false;
Boolean false indicating no insurance
4
if (age >= 18 && hasLicense) {
AND: both age >= 18 AND hasLicense must be true
5
std::cout << "Can drive legally" << std::endl;
Output when both conditions are met
6
if (!hasInsurance) {
NOT: executes when hasInsurance is false
7
std::cout << "Need to get insurance" << std::endl;
Output when insurance is missing
8
if (age < 18 || hasLicense == false) {
OR: executes if either condition is true
9
std::cout << "Cannot drive legally" << std::endl;
Output when OR condition is satisfied