Difficulty: Easy
Correct Answer: Error: cannot convert 'const char *' to 'char *'.
Explanation:
Introduction / Context:
This question evaluates const-correct pointer assignments involving string literals. Function fun returns const char pointing to read-only storage, while main tries to store it in a modifiable char.
Given Data / Assumptions:
Concept / Approach:
Assigning const char to char discards qualifiers. This is not allowed in modern, strictly conforming C because it would allow writes through ptr to read-only memory, causing undefined behavior. Compilers issue an error or at least a diagnostic preventing it.
Step-by-Step Solution:
fun() → returns pointer of type const char *.ptr is declared as char * (non-const).Initialization attempts to drop const → constraint violation.Fix by declaring const char *ptr = fun();
Verification / Alternative check:
Try compiling after changing ptr to const char *. The program compiles cleanly. Any attempt to write through ptr (e.g., ptr[0] = 'X') will then be correctly rejected at compile time.
Why Other Options Are Wrong:
“Lvalue required” is irrelevant; the issue is qualifier mismatch. “No error” is incorrect for standard-conforming compilers. “None of above” is unnecessary when (b) states the precise reason.
Common Pitfalls:
Forgetting that string literals are not mutable; believing const can be silently dropped; mixing old K&R compiler behavior with modern C rules.
Final Answer:
Error: cannot convert 'const char *' to 'char *'.
Discussion & Comments