C comma operator in an expression: determine the output. #include<stdio.h> int main() { int i=2; int j = i + (1, 2, 3, 4, 5); printf("%d ", j); return 0; }

Difficulty: Easy

Correct Answer: 7

Explanation:


Introduction / Context:
The comma operator in C evaluates each operand from left to right and yields the value of the last operand. Inside parentheses, a sequence like (1, 2, 3, 4, 5) therefore evaluates to 5. This question tests recognition of the comma operator's semantics when used inside a larger arithmetic expression.


Given Data / Assumptions:

  • i = 2.
  • Expression: j = i + (1, 2, 3, 4, 5).
  • No side effects beyond evaluation order.


Concept / Approach:
The comma operator is often confused with the comma separating function arguments. In expressions, it is a legitimate operator with low precedence whose result is the last subexpression. Parentheses ensure the comma sequence is treated as a single operand to the plus operator.


Step-by-Step Solution:

Evaluate (1, 2, 3, 4, 5): compute each value, result is the last → 5.Compute j = i + 5 = 2 + 5 = 7.printf prints 7.


Verification / Alternative check:
Replace the last value with another number (e.g., ... , 9) to see the output change correspondingly; the earlier values are discarded except for side effects if present.


Why Other Options Are Wrong:

4, 6, 5, or 2 arise from misreading the comma operator as a list or forgetting that only the last value contributes to the result.


Common Pitfalls:
Confusing the comma operator with argument separators; overlooking its low precedence and the need for parentheses to bind it tightly.


Final Answer:
7.

More Questions from Expressions

Discussion & Comments

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