首页 > 技术文章 > C 语言 const 关键字

loongqiang 2014-05-22 11:26 原文

#include <stdio.h>

int main(void){
int i = 1;
int j = 100;
const int * temp = &i;
printf("%d\n",*temp);
i = 2;
printf("%d\n",*temp);
temp = &j;
printf("%d\n",*temp);

return 0;
}

输出

1
2
100

#include <stdio.h>

int main(void){
int i = 1;
int j = 100;
int const * temp = &i;
printf("%d\n",*temp);
i = 2;
printf("%d\n",*temp);
temp = &j;
printf("%d\n",*temp);

return 0;
}

输出

1
2
100

结论

如果const在'*'左边,则表示指针指向的变量的值不可变

如果const在'*'右边,则表示指针的值是不可变的

问题:

i = 2;
printf("%d\n",*temp);
i 重新赋值,*temp指向的值发生改变
怎么解释?
编译器行为,怀疑不能显示通过 *temp修改变量值

推荐阅读