How to modify a const variable in C? (original) (raw)
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". 
In the below program, a read-only variable declared using the const qualifier is tried to modify:
C `
#include <stdio.h> int main() { const int var = 10; var = 15; printf("var = %d\n", var); return 0; }
`
**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.

Below program illustrates this:
C `
#include <stdio.h>
int main() { const int var = 10;
int *ptr = (int *)&var; // Cast away const
*ptr = 20; // Attempt modification
printf("var = %d\n", var);
return 0;}
`
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.
C `
#include <stdio.h>
int main() { int value = 10; const int *ptr = &value;
value = 20; // Allowed
printf("%d\n", *ptr);
return 0;}
`
**Explanation: The object itself is not const, only the pointer is const, so modification is valid.