![]() |
VOOZH | about |
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.
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:
This means modifying it can cause unpredictable results.
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.
👁 discarding const qualifier through non-const pointerNote: 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:
Running the above code may show a warning or the program may:
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.
If the original object was not declared as const, but accessed through a const pointer, then modification is allowed through a non-const pointer.
20
Explanation: The object itself is not const, only the pointer is const, so modification is valid.