7

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.

2

2 Answers 2

12

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.

9

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.

4
  • 1
    "should be avoided at all costs" But what if a person said they'd hurt me if I didn't? :(
    – GManNickG
    Jan 30, 2011 at 6:03
  • 6
    @GMan Sacrificing one's self to prevent UB guarantees a spot in Coding Nirvana where the static keyword has only one meaning and the release date of Perl 6 is known.
    – SiegeX
    Jan 30, 2011 at 6:09
  • You mean they bother with non-Lisp languages in Coding Nirvana?
    – Chris Lutz
    Jan 30, 2011 at 6:58
  • If I was smart enough to write compilers, I'd make one that gave me a new Ferrari every time someone did this.
    – Crowman
    Jul 19, 2013 at 0:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.