Logical vs Bitwise Operators in C
Logical operators (&&, ||, !) for boolean conditions. Bitwise (&, |, ^, ~) for bit manipulation.
Most common confusion for beginners—know the difference!
1. Key Differences
TEXT
Aspect | Logical (&& || !) | Bitwise (& | ^ ~)
----------------|---------------------|-------------------
Operands | Conditions | Integers
Result | 0 or 1 | Full integer
Short-circuit | Yes | No
Usage | if/while conditions | Bit flags, masks
Examples | age>18 && valid | flags & MASK
2. Logical Operators
C
int x = 5, y = 10;
if (x > 0 && y > 0) { // true && true → 1
printf("Both positive\n");
}
// Output: Both positive
Non-zero = true, zero = false. Returns 0/1.
3. Bitwise Operators
C
int x = 5; // 0101
int y = 3; // 0011
int result = x & y; // 0001 = 1
printf("%d\n", result); // 1
Bit-by-bit operation. Returns full integer.
4. Same Input, Different Results
C
int a = 5, b = 3;
printf("a&&b = %d\n", a && b); // 1 (true)
printf("a&b = %d\n", a & b); // 1 (0001)
int c = 0, d = 3;
printf("c&&d = %d\n", c && d); // 0 (false)
printf("c&d = %d\n", c & d); // 0 (0000)
5. Short-Circuit (Logical Only)
C
int* ptr = NULL;
// SAFE - logical
if (ptr != NULL && *ptr > 0) {}
// CRASH - bitwise
if (ptr != NULL & *ptr > 0) {} // *ptr dereferences NULL!
6. When to Use Each
Logical (&&, ||, !): Conditions, if statements, loops
C
if (age >= 18 && salary > 0 && validID)
if (choice == 1 || choice == 2 || choice == 3)
Bitwise (&, |, ^, ~): Flags, permissions, masks
C
flags |= READ_PERMISSION;
if (flags & WRITE_PERMISSION)
value = x ^ 1; // flip bit 0
7. Quick Quiz
Predict outputs:
C
int x = 7; // 0111
printf("%d %d\n", x && 2, x & 2);
Answer: 1 2 ✓
Conclusion
Rule: Use logical for decisions, bitwise for bits.
Never use &/| in if conditions unless you understand the consequences.
Codecrown