why const object can be changed?

From: Yong (netclassic_at_sina.com)
Date: 10/05/04


Date: Tue, 5 Oct 2004 21:15:29 +0800

Hello,

I have some questions in using keyword "const".Just look the code below

#include <stdio.h>
int main(){
    const int c = 12;
    int *p=(int *)&c;
    *p = 3;
    printf("%d,%d",c,*p);
    return 0;
}

the output would be:
12,3 //why?? *p should be same as c, but...

But if I rewrite my code in this way
#include <stdio.h>
const int c = 12;
int main(){
    //const int c = 12;
    int *p=(int *)&c;
    *p = 3;
    printf("%d,%d",c,*p);
    return 0;
}

there will be a runtime error in line : *p=3 .

I compiled it with g++ and vc7.1 and the results are same.

My question is why the value of *p can be changed in the former condition
but not in the latter.

Thanks



Relevant Pages

  • Re: inline assembly
    ... The word 'asm' is a syntax error. ... named asm which takes char * and returns int, ... The keyword asm has been a part of the C language for a long time. ... The following extensions are widely used in many systems, ...
    (comp.lang.c)
  • Re: FK Constraint Violation upon INSERT
    ... it's better to also set the ResyncCommand. ... unique indexe and the primary key; especially if their names don't come ... int', 0 ... keyword_question.questionid, ...
    (microsoft.public.access.adp.sqlserver)
  • Re: FK Constraint Violation upon INSERT
    ... Using this as the value for the resynch command... ... In profiler I get this under RPC: ... int', 0 ... keyword_question.questionid, ...
    (microsoft.public.access.adp.sqlserver)
  • Re: functools.partial doesnt work without using named parameter
    ... yet the example from the docs of wrapping int to ... create basetwo doesn't need this? ... the keyword argument 2 gets bound to the second. ... spam, ham, eggs are conventions in Python, ...
    (comp.lang.python)
  • Re: Restricting pointer access to zero offset?
    ... Here is a list of pointer properties and associated control ... Keyword "const" prevents these operations. ... Pointer may be used to reference memory at an offset by ... int *var; ...
    (comp.lang.c)