03. Logical Operators & Short-Circuit Evaluation
🟢 Difficulty: Beginner | Boolean Logic, Short-Circuit Guarantees & Safety Checks
📖 Definition
Logical operators in C combine or invert truth values of relational conditions. C provides three logical operators: && (Logical AND), || (Logical OR), and ! (Logical NOT unary operator). Logical expressions evaluate to integer 1 (true) or integer 0 (false).
🎯 Why It Is Used
- Complex Condition Validation: Combining multiple validation rules (e.g.
age >= 18 && has_license == 1). - Short-Circuit Guard Protection: Preventing null pointer dereferences or division-by-zero errors in conditional checks (e.g.
if (ptr != NULL && *ptr == 42)).
⚙️ How It Works: Short-Circuit Evaluation Rules
ISO C guarantees Short-Circuit Evaluation for && and || operators:
- In
A && B: IfAevaluates to false (0), expressionBis NEVER evaluated. - In
A || B: IfAevaluates to true (non-zero), expressionBis NEVER evaluated.
There is a sequence point between the evaluation of A and B.
📝 Syntax & Truth Table
| Operator | Name | Truth Condition | Evaluated Result |
|---|---|---|---|
A && B | Logical AND | True ONLY if BOTH A and B are non-zero. | 1 or 0 |
A || B | Logical OR | True if AT LEAST ONE of A or B is non-zero. | 1 or 0 |
!A | Logical NOT | Inverts truth value: returns 1 if A is 0, and 0 if A is non-zero. | 1 or 0 |
🔀 Bitwise vs Logical Operator Distinction
Do not confuse logical operators (&&, ||) with bitwise operators (&, |)! Bitwise & operates on individual binary bits without short-circuiting, whereas logical && operates on overall boolean truth values with short-circuit evaluation.
🌱 Beginner Example
#include <stdio.h>
#include <stdbool.h>
int main(void) {
bool has_id = true;
int age = 20;
if (has_id && age >= 18) {
printf("Entry Granted!\n");
} else {
printf("Entry Denied!\n");
}
return 0;
}
🌼 Intermediate Example: Null Pointer Guard Protection
#include <stdio.h>
int main(void) {
int *data_ptr = NULL; // Null pointer
// SAFE: Short-circuit evaluation prevents evaluating *data_ptr when data_ptr is NULL!
if (data_ptr != NULL && *data_ptr == 100) {
printf("Data value matches!\n");
} else {
printf("Pointer guard protected program from segmentation fault crash!\n");
}
return 0;
}
🌲 Advanced Example: Side Effects in Short-Circuited Operands
#include <stdio.h>
int increment_counter(int *counter) {
printf("[Side Effect Triggered] Incrementing counter...\n");
(*counter)++;
return 1;
}
int main(void) {
int count = 0;
printf("=== Test 1: First operand is False (0) ===\n");
if (0 && increment_counter(&count)) {
printf("Inside if block\n");
}
printf("Count value after Test 1: %d (Function was skipped due to short-circuit!)\n\n", count);
printf("=== Test 2: First operand is True (1) ===\n");
if (1 && increment_counter(&count)) {
printf("Inside if block\n");
}
printf("Count value after Test 2: %d (Function was executed!)\n", count);
return 0;
}
🔍 Line-by-Line Explanation
if (data_ptr != NULL && *data_ptr == 100): Left expressiondata_ptr != NULLevaluates to false (0), so*data_ptr == 100is never reached, preventing a crash.if (0 && increment_counter(&count)): Because the left operand is0,increment_counter()is never called.
💻 Expected Terminal Output
Pointer guard protected program from segmentation fault crash!
=== Test 1: First operand is False (0) ===
Count value after Test 1: 0 (Function was skipped due to short-circuit!)
=== Test 2: First operand is True (1) ===
[Side Effect Triggered] Incrementing counter...
Inside if block
Count value after Test 2: 1 (Function was executed!)
⚠️ Common Mistakes & Pitfalls
- Relying on Side-Effects in Right Operands: Placing state-modifying functions or
x++inside the right operand of&&or||, causing non-execution when short-circuited. - Confusing Bitwise
&with Logical&&: Using bitwise&disables short-circuit protection and will cause a crash when checking pointers (e.g.ptr != NULL & *ptr == 5crashes!).
📌 Important Rules & Limitations
- Short-circuit evaluation is guaranteed by ISO C for
&&and||. - Logical NOT (
!) turns any non-zero value to0, and0to1.
🌐 Multilingual Explanation: English
Logical operators combine truth conditions (&&, ||, !). Short-circuit evaluation guarantees that if the left operand determines the overall truth value, the right operand is completely skipped.
🌐 Multilingual Explanation: Hindi (Roman Script)
Logical operators && (AND), || (OR), aur ! (NOT) ka upyog multiple conditions ko milane ke liye hota hai. Short-circuiting ki wajah se agar pehla part hi result tay kar deta hai, toh doosra part run nahi hota.
🌐 Multilingual Explanation: Marathi (Roman Script)
Logical operators multiple conditions check karnyasathi vapartat. Short-circuiting mule jar pahili condition bghun uttar tharat asel tar dusri condition execute hot nahi.
❓ Practice Questions
- What is short-circuit evaluation in C?
- Why is bitwise
&dangerous when guarding pointer dereferences compared to logical&&? - What is the value of
!(10 > 5)?
🚀 Practical Coding Challenge
Write a program named access_control.c that checks whether a user gets system access based on three variables: is_admin (bool), has_valid_key (bool), and login_attempts (int). Grant access if user is admin OR (has valid key AND login attempts < 3).
🧭 Navigation & Breadcrumbs
← Previous: 02. Relational Operators | Module 05 Guide | Next: 04. Bitwise Operators →