我的代码:
#include <stdio.h>
main()
{
const int x = 10;
int *p;
p=&x;
*p=20;
printf("Value at p: %d \n",*p);
printf("Value at x: %d", x);
}
我得到的输出是:
p 值:20
x 值:20
因此,常量变量的值被改变。这是使用指针的缺点之一吗?
You used a int*
to point to a const
int. you should get:
error: invalid conversion from ‘const int*’ to ‘int*’
when you do:
p = &x;
You probably needs to update your compiler, a decent compiler should have told you this error or at least gave you warning about this.
That's because you are using the C language in the wrong way and the compiler let you compile this code while giving only a warning
warning: assignment discards ‘const’ qualifier from pointer target type [enabled by default]
And there are answers for that on SO, such as warning: assignment discards qualifiers from pointer target type
Any decent compiler will tell you that you are discarding the const qualifier.
C assumes that the programmer is always right, hence it's your choice to ignore your compiler's warnings or not. As usual, this is not a disadvantage as long as you know what you're doing!
正如其他答案所指出的那样,编写一个程序来尝试修改这样的const
限定变量会导致程序具有未定义的行为。这意味着您的程序可以做任何事情——例如,当我在启用优化的情况下编译您的程序时,我会看到以下输出:
Value at p: 20
Value at x: 10
..如果我将static
限定符添加到变量中,x
那么程序会在运行时崩溃。