Binding a const to a non-const value: After int y = 128; const int x = y; what is printed by printf("%d ", x)?

Difficulty: Easy

Correct Answer: 128

Explanation:


Introduction / Context:
The const qualifier stops further mutation through the declared name, but it does not alter the stored value at initialization. Assigning or initializing a const from an ordinary variable is routine and results in an independent read-only object that holds the copied value at that moment. This question reinforces that constness affects mutability, not representable values or printing behavior.


Given Data / Assumptions:

  • int y = 128;
  • const int x = y;
  • We print x using %d.


Concept / Approach:

  • Initialization copies the value of y into x; x is then read-only.
  • There is no type mismatch: both are of type int; const is a qualifier on x's object, not a different base type.
  • Therefore, printing x yields 128.


Step-by-Step Solution:

Compute initial state: y holds 128.Initialize const int x with y → x = 128.Print x → output 128.


Verification / Alternative check:

Changing y later would not affect x; x remains 128 since it is a distinct object.


Why Other Options Are Wrong:

  • Garbage value/0: contradicts straightforward initialization.
  • Error: no rule forbids initializing a const int from a non-const int.
  • Unspecified behavior: there is no unspecified behavior in this sequence.


Common Pitfalls:

  • Confusing const int x = y; with binding a reference (a C++ concept). In C, it is simply value initialization.
  • Thinking that const implies compile-time constness; here it is a runtime copy but a read-only one thereafter.


Final Answer:

128

More Questions from Constants

Discussion & Comments

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