Menu

breaking const references

Ron McHugh
2008-11-13
2012-09-26
  • Ron McHugh

    Ron McHugh - 2008-11-13

    Check this out...
    [code]

    include <stdio.h>

    void KillConstFloat(const float &f)
    {
    // invert the sign bit.
    (int)&f ^= 0x80000000;
    }

    int main(int argc, char **argv)
    {
    // Scenario 1 - value is const
    //
    // dev-c++ just ignores it.
    // ms-vc6 lets it get trashed.
    //
    const float f = 12.34F;

    // Scenario 2 - value is not const
    //
    // dev-c++ lets it get trashed.
    // ms-vc6 lets it get trashed.
    //
    float f = 12.34F;

    // Comment out one or the other
    // and run this to see it happen.
    //
    KillConstFloat(f);
    printf("%f\n",f);
    return 0;
    }
    [/code]

     

    Related

    Code: code

    • cpns

      cpns - 2008-11-13

      I think all observations are valid, because the result of an attempt to modify a const through a C cast is undefined.

      I ran it in VC++ 2008, and the value was not modified in either case. I have not tried Dev-C++. A C style cast is a brutal thing, that is why C++ has safer alternatives. It is equivalent to:

      reinterpret_cast<int>(const_cast<float*>(&f)) ^= 0x80000000;

      However a const_cast does not turn a const into a non const, it merely allows you to pass a const as a non const parameter. This is useful when using existing code or third-party code that does may not employ absolute const-safety within a function that does.

      The const qualifier causes a compile time check but not necessarily a runtime check. Whether or not the value becomes modifiable would depend upon whether the compiler actually generated a const object or merely placed a literal constant in the code. Normally an object is not instantiated unless an attempt yo take its address appears in the code.

      I would not be surprised if you got different results again with various optimisation settings.

      Clifford

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.