Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of const qualifier if I can modify it through a pointer in C? [duplicate]

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.

like image 606
infinitloop Avatar asked Jan 30 '11 05:01

infinitloop


2 Answers

The reason you could modify the value is because you did a pointer typecast that stripped off the constness:

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 constness 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.

like image 193
templatetypedef Avatar answered Sep 27 '22 16:09

templatetypedef


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.

like image 37
SiegeX Avatar answered Sep 27 '22 16:09

SiegeX