Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Anvi Jain

In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization. In this section we will see how to change the value of some constant variables.

If we want to change the value of constant variable, it will generate compile time error. Please check the following code to get the better idea.

Example

#include <stdio.h>
main() {
   const int x = 10; //define constant int
   printf("x = %d\n", x);
   x = 15; //trying to update constant value
   printf("x = %d\n", x);
}

Output

[Error] assignment of read-only variable 'x'

So this is generating an error. Now we will see how we can change the value of x (which is a constant variable).

To change the value of x, we can use pointers. One pointer will point the x. Now using pointer if we update it, it will not generate any error.

Example

#include <stdio.h>
main() {
   const int x = 10; //define constant int
   int *ptr;
   printf("x = %d\n", x);
   ptr = &x; //ptr points the variable x
   *ptr = 15; //Updating through pointer
   printf("x = %d\n", x);
}

Output

x = 10
x = 15

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.