Re: const_cast<>

From: Jack Klein (jackklein_at_spamcop.net)
Date: 11/13/03


Date: Thu, 13 Nov 2003 04:58:29 GMT

On Thu, 13 Nov 2003 10:06:02 +0530, "R. Anbeeswaran"
<Ramachandran.Anbeeswaran@sisl.co.in> wrote in comp.lang.c++:

> Hi All,
>
> void main()

There is no such thing as "void main()" in C++. The ANSI/ISO standard
requires "int main()" ALWAYS. In fact, a conforming C compiler is
required to issue a diagnostic message for "void main()".

> {
> const int i = 20;
> int *p = const_cast<int*>(&i);
>

Attempting to modify a variable that was defined as const produces
undefined behavior. The C++ standard no longer knows or cares what
your program does. Anything that happens is just as right or wrong as
anything else.

> cout <<"i="<< i <<"\t"<<"*p="<<*p<<"\n";
> }
>
> In the output of the prog. is :
>
> i=20 *p=40
>
> How is it true? (p is pointing to i). How is the particular address
> referenced to two different values?
> In the Quick Watch, (Visutal Studio is used for compilation & debug),
> the value of 'i' and '*p' are same. But, it is flashed out with the
> different values? The result is same in the release mode also.
>
> All assistance are appreciated.

There is no point in asking why a particular compiler produces any
particular results once you invoke undefined behavior.

-- 
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


Relevant Pages

  • Re: faster access private or public?
    ... > void g ... Only if the compiler can somehow prove that this code is always called ... in a context where it causes undefined behavior. ... > in this part of the code while optimizing some other piece of code? ...
    (microsoft.public.vc.language)
  • Re: how to release memory?
    ... interest is that a pointer p is indeterminate. ... except that the compiler is free to optimize the statement away ... Is 'expr;' really invoking undefined behavior if expr's value ... standard doesn't ever say you cannot dereference a void*, ...
    (comp.lang.c)
  • Re: compiler error
    ... the compiler would not do what he reports. ... In the face of undefined behavior, ... halting translation and issuing a diagnostic message. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Function with unspecified number of arguments
    ... void f ... The function body above defines a function that accepts NO ARGUMENTS ... undefined behavior. ... All you did was tell the compiler not to check that you called f ...
    (comp.lang.c)
  • Re: fields for methods?
    ... void A::foo{ ... but only by a compiler that is allowed to ... int static_instance i = 0; ... it totally breaks the idea of encapsulation, which is the reason a lot ...
    (comp.programming)