Topic 11 of 83
Logical & Bitwise
Overview
Logical operators (&&, ||, !) combine conditions. Bitwise operators (&, |, ^, <<, >>) manipulate bits directly for high-performance tasks. Miscellaneous operators include `sizeof`.
Syntax
cpp
bool x = true, y = false;
// Logical
bool andRes = x && y; // false
bool orRes = x || y; // true
bool notRes = !x; // false
// Bitwise
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int bitAnd = a & b; // 0001 (1)
int bitXor = a ^ b; // 0110 (6)
int leftShift = a << 1; // 1010 (10) - multiplies by 2
// Misc
int size = sizeof(a); // 4 bytesCommon Pitfalls
- Confusing logical AND `&&` with bitwise AND `&`.
Interview Tips
- Explain Short-Circuit Evaluation: In `(A && B)`, if A is false, B is never evaluated. This prevents errors like division by zero or null pointer dereferencing.
- Bitwise operations are heavily tested in algorithmic interviews (e.g., checking if a number is a power of 2 using `(n & (n-1)) == 0`).
Real-World Example
Using logical operators for multiple conditions.
example
cpp
#include <iostream>
using namespace std;
int main() {
int age = 25;
bool hasLicense = true;
if (age >= 18 && hasLicense) {
cout << "Can drive!\n";
}
return 0;
}