Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

c++ - 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
",*ip);
    printf("%d
",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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...