Dereferencing a pointer-to-const bound to a const object: With const int x = 5; const int *ptrx = &x; what happens when executing *ptrx = 10; then printing x?

Difficulty: Easy

Correct Answer: Error

Explanation:


Introduction / Context:
In C, a pointer declared as const int * is a pointer to a read-only integer. The qualifier applies to the pointed-to object as accessed through that pointer. Attempting to assign through such a pointer is forbidden and should trigger a compiler error, safeguarding program correctness by preventing unintended writes to protected data.


Given Data / Assumptions:

  • const int x = 5;
  • const int *ptrx = &x;
  • Statement: *ptrx = 10; followed by printing x.


Concept / Approach:

  • The expression *ptrx designates a non-modifiable lvalue because ptrx points to const-qualified int.
  • Assigning a new value to a non-modifiable lvalue is illegal; compilers issue messages like 'assignment of read-only location'.
  • Therefore, the program fails to compile at the assignment; no runtime output is produced.


Step-by-Step Solution:

Determine the effective type of *ptrx → const int.Check assignment legality → writing to const object → not allowed.Compilation error occurs; the printf is never reached.


Verification / Alternative check:

If ptrx were declared int * and pointed to a non-const int, *ptrx = 10 would be valid. If you tried to cast away const and still write, behavior would be undefined even if it appears to work on some platforms.


Why Other Options Are Wrong:

  • 5 or 10: imply successful execution, but the assignment will not compile.
  • Garbage value: not applicable; the code does not run.
  • Warning-only scenario: standards-compliant compilers treat this as an error when you attempt the assignment.


Common Pitfalls:

  • Misunderstanding that const applies to the pointer vs the pointee; here, the pointee is const.
  • Believing that casting away const makes it safe to write; it does not if the original object was defined const.


Final Answer:

Error

More Questions from Constants

Discussion & Comments

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