C logical OR (||) evaluation: what does this program output? #include<stdio.h> int main() { int x=12, y=7, z; z = x!=4 || y == 2; printf("z=%d ", z); return 0; }

Difficulty: Easy

Correct Answer: z=1

Explanation:


Introduction / Context:
Logical operators in C convert relational results to either 0 (false) or 1 (true). This simple example reinforces that comparisons yield 0 or 1 and that the logical OR operator short-circuits once a true operand is found.


Given Data / Assumptions:

  • x = 12, y = 7.
  • Expression: z = (x != 4) || (y == 2).
  • Standard C semantics for relational and logical operators.


Concept / Approach:
Evaluate the left comparison first: x != 4 is true (12 is not 4), which yields 1. Since || short-circuits, the right side does not affect the final result; z is set to 1. The printf prints z as “1”.


Step-by-Step Solution:

Compute x != 4 → true → 1.Because the left operand of || is 1, the expression is already true.No need to evaluate y == 2; z becomes 1.printf formats as “z=1”.


Verification / Alternative check:
Replace y with any value; as long as x != 4 remains true, z stays 1. Conversely, set x to 4 and y to 2 to see z remain 1 due to the right operand.


Why Other Options Are Wrong:

z=0 contradicts true OR anything.z=4 or z=2 confuses arithmetic with logical results (which are 0 or 1).z=-1 is not a standard logical result in C for this expression.


Common Pitfalls:
Thinking relational operators return operands themselves; in C99+ the result is guaranteed 0 or 1 for these logical forms.


Final Answer:
z=1.

More Questions from Expressions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion