Const object initialization rule in C: diagnosing assignment after declaration
#include
int main()
{
const int x; /* uninitialized /
x = 128; / attempted assignment after declaration */
printf("%d
", x);
return 0;
}
-
AError: unknown data type const int
-
BError: const variable have been initialised when declared.
-
CError: stack overflow in x
-
DNo error
-
EOnly a warning; value becomes 128
Answer
Correct Answer: Error: const variable have been initialised when declared.
Explanation
Introduction / Context:This question evaluates understanding of const object initialization in C. A const object must be initialized at the point of its definition; further assignments are not allowed.
Given Data / Assumptions:
- x is declared as const int without an initializer.
- Later, x = 128 attempts to assign a new value.
- Standard C rules apply.
Concept / Approach:Declaring const int x; creates a read-only object. Because it cannot be assigned to after declaration, you must initialize it immediately, e.g., const int x = 128;. Attempting to assign later violates const, producing a compile-time error.
Step-by-Step Solution:Parse declaration: const int x; → needs initializer to set value.Line x = 128; → illegal: assignment to const object.Fix by writing const int x = 128; and removing the later assignment.
Verification / Alternative check:Compile both versions: the incorrect one fails; the corrected one compiles and prints 128.
Why Other Options Are Wrong:(a) “unknown data type” is false—const int is valid. (c) “stack overflow” is irrelevant. (d) claims no error, which is incorrect.
Common Pitfalls:Believing const only prevents taking the address or only applies to pointer targets; assuming you can “set once later.”
Final Answer:Error: const variable have been initialised when declared.