Mail Archives: djgpp/2001/07/19/01:02:06
On Wed, 18 Jul 2001 21:41:11 +0530, Prashant Ramachandra
<rprash AT wilco-int DOT com> wrote in comp.os.msdos.djgpp:
> I have a question that's probably got nothing to with DJGPP, so please
> forgive me for this off-topic post.
>
> I tried the program below and interestingly, it gives me...
>
> "Constant is 10. It is actually 1"
>
> Shouldn't gcc not make the assumption that the value of j *is* 10 and
> instead reference itfrom memory instead.
>
> > Program:
> >
> > #include <iostream.h>
> >
> > class Test {
> > public:
> > static const int i;
> >
> > void run () { cout << i << endl; }
> > Test () { }
> > };
> >
> > const int Test::i = 7;
> >
> > const int j = 10;
> >
> > int main ()
> > {
> > Test t1;
> > Test t2;
> >
> > int *k = (int *)&j;
> > *k = 1;
> > cout << "Constant is " << j << ". It is actually " << *k << endl;
> > t1.run ();
> > t2.run ();
> > }
> >
> Thanks a lot for any explanations.
>
> Regards,
> Prashant
1. You should be using const_cast in C++ to remove the const
qualifier from a constant pointer.
2. The minute you attempt to modify the value of an object defined
with a const qualifier you invoke undefined behavior. You have no
recourse at all to the C++ standard for the result, the ANSI/ISO
standard specifically states that undefined behavior is that for which
the language standard imposes no requirements at all.
3. What you have made here is no longer a C++ program. If it printed
42 it would be just as correct as far as C++ is concerned.
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
- Raw text -