Const-correctness check in C: assigning a const char* to a non-const char* variable\n\n#include<stdio.h>\nconst char *fun();\n\nint main()\n{\n char *ptr = fun();\n return 0;\n}\nconst char *fun()\n{\n return "Hello";\n}

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:

  • fun() returns const char .
  • main defines char ptr and initializes it with fun().
  • String literals reside in read-only memory in most C implementations.


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 *'.

More Questions from Constants

Discussion & Comments

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