C Logical Operators in Conditions
🔗 C Logical Operators in Conditions (Beginner → Advanced)
In C language, logical operators are used to combine or modify conditions.
They are most commonly used in if statements, loops, and conditional expressions.
1️⃣ What Are Logical Operators?
Logical operators work with conditions (true/false) and return either 1 (true) or 0 (false).
C has three logical operators:
| Operator | Name | Meaning |
|---|---|---|
&& |
Logical AND | All conditions must be true |
|
||
! |
Logical NOT | Reverses the condition |
2️⃣ Logical AND (&&) ⭐
Rule
✔ Result is true only if all conditions are true
Example
✔ Both conditions must be satisfied
3️⃣ Logical OR (||) ⭐
Rule
✔ Result is true if any one condition is true
Example
✔ Only one condition is enough
4️⃣ Logical NOT (!) ⭐
Rule
✔ Reverses the result of a condition
Example
✔ !0 → 1 (true)
✔ !1 → 0 (false)
5️⃣ Using Logical Operators in if-else
✔ Common in grading systems
6️⃣ Logical Operators with while Loop ⭐
✔ Loop runs only while condition is true
7️⃣ Logical Operators with for Loop
✔ Stops when i == 7
8️⃣ Truth Table (Very Important for Interviews) ⭐
AND (&&)
| A | B | A && B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
OR (||)
| A | B | A || B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
NOT (!)
| A | !A |
|---|---|
| 0 | 1 |
| 1 | 0 |
9️⃣ Short-Circuit Evaluation ⭐ (Very Important)
AND (&&)
✔ Second condition executes only if first is true
OR (||)
✔ Second condition executes only if first is false
📌 Prevents runtime errors (like divide by zero)
🔟 Logical vs Bitwise Operators ⚠️
| Logical | Bitwise |
|---|---|
&& |
& |
| ` | |
! |
~ |
| Works on | Conditions |
| Result | 0 or 1 |
❌ Do NOT confuse them
1️⃣1️⃣ Common Mistakes ❌
❌ Using & instead of &&
❌ Using | instead of ||
❌ Forgetting parentheses
❌ Assuming non-zero means only 1
✔ Any non-zero value is true
📌 Interview Questions (Must Prepare)
-
Difference between
&&and& -
What is short-circuit evaluation?
-
Output of
if (5 && 10)? -
Difference between logical and bitwise operators
-
When
||skips second condition?
🔥 Real-Life Use Cases
-
Login validation (username && password)
-
Range checking
-
Menu conditions
-
Input validation
-
Loop control
✅ Summary
✔ Logical operators combine conditions
✔ && → all true
✔ || → any true
✔ ! → reverse condition
✔ Short-circuit improves safety
✔ Essential for conditions, loops & interviews
