Possible Duplicate:
Does the evil cast get trumped by the evil compiler?
Hello,
If I can modify a constant through a pointer, then what is the purpose of it? Below is 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:
Before: 10
After: 2
Press any key to continue . . .
Using Visual Studio 2008.
The reason you could modify the value is because you did a pointer typecast that stripped off the const
ness:
int *p = (int *)&a;
This typecasts a const int*
(namely &a
) to an int *
, allowing you to freely modify the variable. Normally the compiler would warn you about this, but the explicit typecast suppressed the warning.
The main rationale behind const
at all is to prevent you from accidentally modifying something that you promised not to. It's not sacrosanct, as you've seen, and you can cast away const
ness with impunity, much in the same way that you can do other unsafe things like converting pointers to integers or vice-versa. The idea is that you should try your best not to mess with const
, and the compiler will warn you if you do. Of course, adding in a cast tells the compiler "I know what I'm doing," and so in your case the above doesn't generate any sort of warnings.
If i can modify a constant through a pointer then what is the purpose of it? below is code:
This is Undefined Behavior and should be avoided at all costs:
§ C99 6.7.3p5
If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With