VOOZH about

URL: https://www.geeksforgeeks.org/c/how-to-modify-a-const-variable-in-c/

⇱ How to modify a const variable in C? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to modify a const variable in C?

Last Updated : 21 Feb, 2026

Whenever we use const qualifier with variable name, it becomes a read-only variable and get stored in .rodata segment. Any attempt to modify this read-only variable will then result in a compilation error: "assignment of read-only variable". 👁 Image

In the below program, a read-only variable declared using the const qualifier is tried to modify:

Output

prog.c: In function 'main':
prog.c:5:9: error: assignment of read-only variable 'var'

The compiler prevents modification because var is declared as read-only.

Where Is a const Variable Stored

There is a common misconception that const variables are always stored in the .rodata (read-only data) segment. The C standard does not guarantee storage location, the compiler may:

  • Store it in read-only memory
  • Replace it with a literal constant
  • Optimize it away completely

This means modifying it can cause unpredictable results.

Attempting to Modify const Using a Pointer

Variables declared with const are often placed in read-only memory. Earlier, programmers could cast away the const qualifier using a pointer and attempt to modify the value. However, this relies on compiler behavior and results in undefined behavior.

Note: Modern C++ compilers usually produce an error, while C compilers may only show a warning. In either case, modifying a const variable this way is unsafe and should be avoided.

👁 discarding const qualifier through non-const pointer

Below program illustrates this:

Running the above code may show a warning or the program may:

  • Print 10
  • Print 20
  • Crash
  • Behave unpredictably

This is because modifying a const object results in undefined behavior because the C language standards states that if an attempt is made to modify an object defined with const-qualified type, the behavior is undefined.

Modifying Through a Non-const Alias (Special Case)

If the original object was not declared as const, but accessed through a const pointer, then modification is allowed through a non-const pointer.


Output
20

Explanation: The object itself is not const, only the pointer is const, so modification is valid.

Comment