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:
#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'
Changing Value of a const variable through pointer
The variables declared using const keyword, get stored in .rodata segment, but we can still access the variable through the pointer and change the value of that variable. By assigning the address of the variable to a non-constant pointer, We are casting a constant variable to a non-constant pointer. The compiler will give warning while typecasting and will discard the const qualifier. Compiler optimization is different for variables and pointers. That is why we are able to change the value of a constant variable through a non-constant pointer.

Below program illustrates this:
//Write C code here #include<stdio.h> #include<stdlib.h> int main() { const int var = 10; int *ptr = &var; *ptr = 12; printf("var = %d\n", var); return 0; } |
Output:
prog.c: In function 'main':
prog.c:6:16: warning: initialization discards 'const' qualifier
from pointer target type [-Wdiscarded-qualifiers]
int *ptr = &var;
var = 12
Note: If we try to change the value through constant pointer then we will get an error because we are trying to change the read-only segment.
Recommended Posts:
- Difference between const int*, const int * const, and int const *
- Difference between const char *p, char * const p and const char * const p
- Can we access global variable if there is a local variable with same name?
- Const Qualifier in C
- C++ | const keyword | Question 1
- C++ | const keyword | Question 2
- C++ | const keyword | Question 3
- C++ | const keyword | Question 5
- C++ | const keyword | Question 5
- Diffference between #define and const in C?
- Why copy constructor argument should be const in C++?
- Function overloading and const keyword
- “static const” vs “#define” vs “enum”
- How to print a variable name in C?
- Different ways to initialize a variable in C/C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



