Google Search

Saturday, October 24, 2015

How to change value of a constant variable in C

Constant Variables
Constant variables are those which are declared using ‘const’ keyword. For example :
const int count = 0;
The above line declares a constant variable ‘count’ with value zero. The effect of ‘const’ keyword is that after this line the value of ‘count’ cannot be changed. Lets look at the following code :
‪#‎include‬<stdio.h>
int main(void)
{
const int count = 0;
count = 6;
printf("%d\n", count);
return 0;
}
Now, in the second line of function main() in code above, we tried to change the value of a constant variable ‘count’ by assigning it a value of 6. When the above code is compiled, we see :
$ gcc -Wall constptr.c -o constptr
constptr.c: In function ‘main’:
constptr.c:8: error: assignment of read-only variable ‘count’
So we see that the compiler treats ‘count’ as read only variable since we have declared it constant and hence compiler gives an error while modifying its value.
Can the value of a constant be modified?
Well, Yes. This is because of the fact that the keyword ‘const’ puts a restriction only on the name of the variable. This means that the value of the variable ‘count’ cannot be changed through its name but through any other way that does not involve the variable name, yes the value can be changed. For example, we can use pointers to achieve the same. Following is a proof of concept for this :
#include
int main(void)
{
const int count = 0;
int *ptr = &count;
*ptr = 6;
printf("%d\n", count);
return 0;
}
In the code above, a pointer is made to point to the constant variable ‘count’ and through this pointer, the value of count is changed from 0 to 6. When we compile and run the code, we get :
$ ./constptr
6
So we see that the value of constant variable got changed.

No comments:

Post a Comment