What is the purpose of the const constructor if I can change it with a pointer in C?

Possible duplicate:
Is an evil order hidden by an evil compiler?

Hello,

If I can change a constant using a pointer, then what is its purpose? Below is the code:

#include <stdio.h> #include <stdlib.h> int main() { const int a = 10; int *p = (int *)&a; printf("Before: %d \n", a); *p = 2; /*a = 2; gives error*/ printf("After: %d \n", *p); return 0; } 

OUTPUT:

To 10
After: 2
Press any key to continue.,

Using Visual Studio 2008.

+7
source share
2 answers

The reason you can change the value is because you made an order such as a pointer that removed const ness:

 int *p = (int *)&a; 

This method outputs a const int* (namely &a ) to int * , which allows you to freely change the variable. Typically, the compiler warns you about this, but an explicit output type suppresses the warning.

The basic rationale for const is to prevent you from accidentally changing what you promised not to do. This, as you saw, is not inviolable, and you can discard const with impunity, just as you can do other unsafe things, such as converting pointers to integers or vice versa. The idea is that you should try your best not to get confused with const , and the compiler will warn you if you do this. Of course, the addition to the cast tells the compiler “I know what I'm doing,” and so in your case the above does not generate any warnings.

+12
source

If I can change the constant through a pointer, then what is the purpose of this? Below is the code:

This is Undefined Behavior and should be avoided at all costs:

& section; C99 6.7.3p5

If an attempt is made to modify an object defined using the const type command using the value l with a non-constant qualified type, the behavior is undefined .

+9
source

All Articles