Unmodifiable const variables

suggest change
const int a = 0; /* This object cannot be modified through a */
int b = 0;       /* This object can be modified */

b += 10; /* Changes the value of b */
a += 10; /* Constraint violation: a diagnostic is required */

The const qualification only means that we don’t have the right to change the data. It doesn’t mean that the value cannot change behind our back.

_Bool doIt(double const* a) {
   double rememberA = *a;
   // do something long and complicated that calls other functions

   return rememberA == *a;
}

During the execution of the other calls *a might have changed, and so this function may return either false or true.

Warning


Variables with const qualification could still be changed using pointers:

const int a = 0;

int *a_ptr = (int*)&a; /* This conversion must be explicitly done with a cast */
*a_ptr += 10;          /* This has undefined behavior */

printf("a = %d\n", a); /* May print: "a = 10" */

But doing so is an error that leads to undefined behavior. The difficulty here is that this may behave as expected in simple examples as this, but then go wrong when the code grows.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents