James Kanze
11/10/2008 8:36:00 AM
On Nov 9, 4:40 pm, JaredGrubb <jared.gr...@gmail.com> wrote:
> > The pConstValue and pValue both point to the ConstValue, and
> > the value access by the point is changed, but constValue has
> > never changed ( and it shoule not be a constant ). I can not
> > explain, Can somebody help me ?
> You're confusing what "const" means... Const means "you cannot
> change it" and does NOT mean that "it cannot be changed" (your
> program is an example of this!).
It depends. Const has two meanings. In general, you cannot
modify a value throw an expression which refers to an object (an
lvalue expression, in standardese) and has a const type; you can
modify the object through other expressions, however. If the
object itself is const, however (as is the case here), any
attempt to modify it is undefined behavior.
> Change these declarations from "const" to "volatile const" and
> your program will work the way you had hoped (constValue
> returns 1 after *pValue is altered):
It might, or it might not. Undefined behavior is undefined
behavior.
> > volatile const int constValue = 12;
> > volatile const int* pConstValue = &constValue;
The volatile simply tells the compiler that this object might be
modified by something outside the program. Any attempt to
modify it from within the program is still undefined behavior.
As another poster pointed out, declaring the object static could
very well end up in the attempt to modify it causes a core dump.
The volatile probably won't help here.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34