CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2010
    Posts
    1

    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
    Location
    Singapore
    Posts
    6,765

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

    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:

    Code:
    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):
    Code:
    z    = 10	&z   = 0x7fff5fbfc44c
    *x   =15	x    = 0x7fff5fbfc44c
    ref = 15	&ref = 0x7fff5fbfc44c

  4. #4
    Join Date
    Feb 2002
    Posts
    4,640

    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:
    Code:
    cout<< "z= " << z;
    As if it were written as:
    Code:
    cout<< "z= " << 10;
    Viggy

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
  •  





Click Here to Expand Forum to Full Width

Featured