C conditional operator (?:) usage with assignments: Determine the program output and understand why the ternary expression is valid. #include <stdio.h> int main() { int a = 10, b; a >= 5 ? b = 100 : b = 200; printf("%d ", b); return 0; }

Difficulty: Easy

Correct Answer: 100

Explanation:


Introduction / Context:
This item confirms understanding of the conditional operator ?: and how assignment expressions inside each branch are parsed. Many learners suspect the syntax is invalid without extra parentheses, but it is legal and unambiguous in C.


Given Data / Assumptions:

  • a is 10, so a >= 5 is true.
  • The expression is written as a >= 5 ? b = 100 : b = 200;


Concept / Approach:
The conditional operator chooses between two expressions based on the condition. Here, both operands are assignment expressions that set b. When the condition is true, the left operand runs; otherwise, the right operand runs. The entire expression’s value is the result of the chosen assignment expression, but only the side effect (assigning b) matters for the next line.


Step-by-Step Solution:
Evaluate condition: 10 >= 5 → true.Execute true branch: b = 100.Print b → 100.


Verification / Alternative check:
Adding parentheses like (a >= 5) ? (b = 100) : (b = 200); preserves the same behavior and may improve readability. Using a straightforward if/else yields the same result.


Why Other Options Are Wrong:
200 contradicts the true condition. Lvalue required is inapplicable because b is a valid lvalue. Garbage value is wrong since b is definitely assigned.


Common Pitfalls:
Misplacing semicolons as in a >= 5 ? (b = 100) : (b = 200); is fine; the issue is only readability, not correctness.


Final Answer:
100

More Questions from Control Instructions

Discussion & Comments

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