Open In App
Related Articles

How to modify a const variable in C?

Improve Article
Improve
Save Article
Save
Like Article
Like

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.
discarding const qualifier through non-const 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.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 05 Sep, 2018
Like Article
Save Article
Previous
Next
Similar Reads