In C, evaluate logical expressions and operator precedence.
What is the output of the following program?
#include
int main()
{
int i=4, j=-1, k=0, w, x, y, z;
w = i || j || k;
x = i && j && k;
y = i || j && k;
z = i && j || k;
printf("%d, %d, %d, %d
", w, x, y, z);
return 0;
}
-
A1, 1, 1, 1
-
B1, 1, 0, 1
-
C1, 0, 0, 1
-
D1, 0, 1, 1
-
E0, 0, 1, 0
Answer
Correct Answer: 1, 0, 1, 1
Explanation
Introduction / Context:C's logical operators use short-circuit evaluation and defined precedence: && (logical AND) has higher precedence than || (logical OR). Any nonzero integer is treated as true, and zero is false. This problem checks your command of precedence and short-circuit semantics.
Given Data / Assumptions:
- i = 4 (true), j = -1 (true), k = 0 (false).
- Operator precedence: && before ||.
- Logical result values are 0 or 1.
Concept / Approach:Evaluate expressions respecting precedence, then apply short-circuiting: for A || B, if A is true, B is not evaluated; for A && B, if A is false, B is not evaluated. Here, all operands are simple variables, so no side effects complicate evaluation.
Step-by-Step Solution:
w = i || j || k → true || true || false → 1x = i && j && k → true && true && false → 0y = i || (j && k) → j && k is true && false → 0; then i || 0 → 1z = (i && j) || k → i && j is true && true → 1; then 1 || k (false) → 1Verification / Alternative check:Manually substituting 1 for nonzero and 0 for zero reproduces the results, confirming 1, 0, 1, 1.
Why Other Options Are Wrong:
Any option with x = 1 ignores that i && j && k is false because k is 0.Options with y = 0 or z = 0 misapply precedence or OR semantics given the true operands.Common Pitfalls:Forgetting that && binds tighter than ||; assuming nonzero negative values are false (they are true in C).
Final Answer:1, 0, 1, 1.