Search code examples
c++constants

C/C++ changing the value of a const


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 replicate it I'm not being able to put it to compile.

The concept was that it is possible to change by accident the value of a const in C/C++

It was something like this:

const int a = 3;          // I promise I won't change a
const int *ptr_to_a = &a; // I still promise I won't change a
int *ptr;
ptr = ptr_to_a;

(*ptr) = 5;               // I'm a liar; a is now 5

I wanted to show this to a friend but now I'm missing a step. Does anyone know what's missing for it to start compiling and working?

ATM I'm getting invalid conversion from 'const int*' to 'int*' but when I read the article I tried and it worked great.


Solution

  • you need to cast away the constness:

    linux ~ $ cat constTest.c
    #include <stdio.h>
    
    
    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 <iostream>
    using namespace std;
    int main( void )
    {
            const int a = 3; // I promisse i won't change a
            int *ptr;
            ptr = const_cast<int*>( &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.