why const object can be changed?
From: Yong (netclassic_at_sina.com)
Date: 10/05/04
- Next message: Karl Heinz Buchegger: "Re: why const object can be changed?"
- Previous message: Yong: "why const object can be changed?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 5 Oct 2004 21:20:04 +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
- Next message: Karl Heinz Buchegger: "Re: why const object can be changed?"
- Previous message: Yong: "why const object can be changed?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|