Introduction / Context:
Unary increment (postfix or prefix) requires a modifiable lvalue because it actually writes back to the operand after computing its value. When an object is declared const, the language forbids modifying it through that identifier. This question checks your understanding by applying the post-increment operator to a const-qualified integer and observing the result at compile time.
Given Data / Assumptions:
- const int i = 0;
- printf("%d\n", i++);
- Standard C operator semantics apply.
Concept / Approach:
- Post-increment on an expression E evaluates E, then stores E+1 back into the same object.
- Because i is const, storing the new value is not permitted; i is not a modifiable lvalue.
- Therefore, the expression is ill-formed, and the compiler must diagnose it.
Step-by-Step Solution:
Identify operator → i++ requires write-back to i.Check object mutability → i is const → write disallowed.Compilation error occurs; typical messages include 'lvalue required' or 'increment of read-only variable'.
Verification / Alternative check:
Replacing i++ with (i + 1) compiles, because that expression does not modify i; it only computes a temporary value.
Why Other Options Are Wrong:
- 10/11: imply successful execution and arithmetic; code will not compile.
- No output: implies runtime suppression; the failure happens at compile time.
- Undefined behavior: the standard forbids the operation; a diagnostic is required.
Common Pitfalls:
- Confusing const with compile-time constant: the issue here is mutability, not evaluation timing.
- Assuming prefix ++i would differ; both require a modifiable lvalue and are equally invalid on const.
Final Answer:
Error: ++needs a value
Discussion & Comments