Skip to content
Related Articles

Related Articles

How to modify a const variable in C?
  • Difficulty Level : Basic
  • Last Updated : 05 Sep, 2018

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.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :