How to modify a const variable in C?

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
int main()
{
    const int var = 10;
    var = 15;
    printf("var = %d\n", var);
    return 0;
}
chevron_right

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

//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;
}
chevron_right

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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.





Check out this Author's contributed articles.

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.


Article Tags :
C
Practice Tags :