【发布时间】:2013-05-06 01:30:07
【问题描述】:
我的代码:
#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
因此,常量变量的值发生了变化。这是使用指针的缺点之一吗?
【问题讨论】:
-
C 不会阻止你做这样的蠢事。不过,您确实会收到编译器的警告:
const.c:9: warning: assignment discards qualifiers from pointer target type -
#include "stdio.h"=>#include <stdio.h> -
请注意,根据启用的编译器和优化,您可能会在输出“x 处的值:10”中得到。
-
我能看到的 C 语言中唯一有用的
const是在参数中。