delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/07/19/01:02:06

From: Jack Klein <jackklein AT spamcop DOT net>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: [OT] About const int
Message-ID: <3gpcltkrvp96qmjnj005rfi31hfo38q296@4ax.com>
References: <5BF60CD649EDD411A04600B0D049F53AFFA913 AT hydmail02 DOT hyd DOT wilco-int DOT com>
X-Newsreader: Forte Agent 1.8/32.548
MIME-Version: 1.0
Lines: 65
Date: Thu, 19 Jul 2001 04:48:14 GMT
NNTP-Posting-Host: 12.84.12.123
X-Complaints-To: abuse AT worldnet DOT att DOT net
X-Trace: bgtnsc04-news.ops.worldnet.att.net 995518094 12.84.12.123 (Thu, 19 Jul 2001 04:48:14 GMT)
NNTP-Posting-Date: Thu, 19 Jul 2001 04:48:14 GMT
Organization: AT&T Worldnet
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019