Uninitialized variable inside a conditional path: determine printed values #include<stdio.h> int main() { int a = 300, b, c; if(a >= 400) b = 300; c = 200; printf("%d, %d, %d ", a, b, c); return 0; }
-
A300, 300, 200
-
BGarbage, 300, 200
-
C300, Garbage, 200
-
D300, 300, Garbage
-
ECompilation error
Answer
Correct Answer: 300, Garbage, 200
Explanation
Introduction / Context:This checks understanding of definite assignment and reading uninitialized automatic variables. The program conditionally assigns to b but always prints it, regardless of whether the condition executed.
Given Data / Assumptions:
- a = 300 so the condition a >= 400 is false.
- b is an automatic int with indeterminate initial value.
- c is assigned 200 before printing.
Concept / Approach:In C, local automatic variables without an initializer contain indeterminate values. If the path that initializes b does not execute, printing b invokes undefined behavior (typically it appears as a “garbage” number). a and c are well-defined.
Step-by-Step Solution:Evaluate condition: 300 >= 400 → false, so b is not set.Set c = 200.Print a (300), b (indeterminate), c (200).
Verification / Alternative check:Initialize b to a known value (e.g., int b = 0;) to get deterministic output 300, 0, 200. Alternatively, place an else branch that initializes b when the if is false.
Why Other Options Are Wrong:“300, 300, 200” assumes the if branch executed. “Garbage, 300, 200” misplaces the garbage value on a, which is initialized. “300, 300, Garbage” is wrong because c is definitely assigned.
Common Pitfalls:Assuming locals default to 0; forgetting that reading an uninitialized variable is undefined; misinterpreting compiler warnings as safe behavior.
Final Answer:300, Garbage, 200