C/C++ changing the value of a const

后端 未结 18 1856
醉梦人生
醉梦人生 2020-11-28 07:28

I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to repli

18条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 07:40

    you need to cast away the constness:

    linux ~ $ cat constTest.c
    #include 
    
    
    void modA( int *x )
    {
            *x = 7;
    }
    
    
    int main( void )
    {
    
            const int a = 3; // I promisse i won't change a
            int *ptr;
            ptr = (int*)( &a );
    
            printf( "A=%d\n", a );
            *ptr = 5; // I'm a liar, a is now 5
            printf( "A=%d\n", a );
    
            *((int*)(&a)) = 6;
            printf( "A=%d\n", a );
    
            modA( (int*)( &a ));
            printf( "A=%d\n", a );
    
            return 0;
    }
    linux ~ $ gcc constTest.c -o constTest
    linux ~ $ ./constTest
    A=3
    A=5
    A=6
    A=7
    linux ~ $ g++ constTest.c -o constTest
    linux ~ $ ./constTest
    A=3
    A=3
    A=3
    A=3
    

    also the common answer doesn't work in g++ 4.1.2

    linux ~ $ cat constTest2.cpp
    #include 
    using namespace std;
    int main( void )
    {
            const int a = 3; // I promisse i won't change a
            int *ptr;
            ptr = const_cast( &a );
    
            cout << "A=" << a << endl;
            *ptr = 5; // I'm a liar, a is now 5
            cout << "A=" << a << endl;
    
            return 0;
    }
    linux ~ $ g++ constTest2.cpp -o constTest2
    linux ~ $ ./constTest2
    A=3
    A=3
    linux ~ $
    

    btw.. this is never recommended... I found that g++ doesn't allow this to happen.. so that may be the issue you are experiencing.

提交回复
热议问题