Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const variable changed with pointer in C

The variable i is declared const but still I am able to change the value with a pointer to the memory location to it. How is it possible?

int main()
{

    const int i = 11;
    int *ip = &i;
    *ip=100;
    printf("%d\n",*ip);
    printf("%d\n",i);
}

When I compile, I get this warning :

test.c: In function ‘main’:
test.c:11: warning: initialization discards qualifiers from pointer target type

Output is this

100
100
like image 330
user995487 Avatar asked Nov 29 '22 15:11

user995487


2 Answers

const is a compile-time feature.
It doesn't prevent you from shooting yourself in the foot; that's what the warning is for.

like image 180
SLaks Avatar answered Dec 15 '22 20:12

SLaks


The const is not a request to the compiler to make it impossible to change that variable. Rather, it is a promise to the compiler that you won't. If you break your promise, your program is allowed to do anything at all, including crash.

For example, if I compile your example code using gcc with the -O2 optimisation level, the output is:

100
11

The compiler is allowed to place a const qualified variable in read-only memory, but it doesn't have to (apart from anything else, some environments don't implement any such thing). In particular, it is almost always impractical for automatic ("local") variables to be placed in read-only memory.

If you change the declaration of of i to:

static const int i = 11;

then you may well find that the program now crashes at runtime.

like image 29
caf Avatar answered Dec 15 '22 20:12

caf