const_cast does not modify variables value
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums
Results 1 to 4 of 4

Thread: const_cast does not modify variables value

  1. #1
    Join Date
    Jan 2010

    const_cast does not modify variables value

    const int z = 10;
    const int *x = &z;
    *const_cast <int *> (x) = 1;
    const int &ref = z;

    const_cast<int &> (ref) = 15;

    cout<< "z= " << z;
    cout <<"*x ="<<*x;
    cout << "ref = "<<ref;

    Output seen

    z = 10

    *x = 15;

    ref = 15

    how can z be 10 if its reference and value at its address is 15. is a separate copy of z kept ?

  2. #2
    Join Date
    Jan 2006

    Re: const_cast does not modify variables value

    If I remember correctly, you are looking at the result of undefined behaviour: that of trying to modify something that is really const.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Feb 2009

    Re: const_cast does not modify variables value

    Laserlight is correct, undefined behaviour

    Given below is my understanding:
    Don't modify the value of the variable for which constness is removed. If you do, then it is results in undefined behaviour.

    The only use of const_cast is in the below mentioned scenario:

    void f1(int& pValue1)
        //pValue1 is however not modified inside f1
        //pValue1 is only used as rvalue (never should it use pValue1 as lvalue)
    void f2(const int& pValue2)
        f1( const_cast<int&>((pValue2)) );

    For reference, code output of the original program (after modification to print the address):
    z    = 10	&z   = 0x7fff5fbfc44c
    *x   =15	x    = 0x7fff5fbfc44c
    ref = 15	&ref = 0x7fff5fbfc44c

  4. #4
    Join Date
    Feb 2002

    Re: const_cast does not modify variables value

    As others have already said, this is undefined behavior. However, one optimization technique is to replace all const variables by their actual value. So, if you were to look at the assembly, you'd probably see that the compiler compiled the following line:
    cout<< "z= " << z;
    As if it were written as:
    cout<< "z= " << 10;

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)