const修飾變量是常用的,不容易犯錯,而const和指針一起使用時很容易混淆。
(一)const int *p
#include <stdio.h>
int main(void)
{
int a = 10;
int b = 20;
const int *p = &a;
*p = b;
return 0;
}
const在int *的左側,即指針指向內容爲常量,所以p指向的內容不允許修改,編譯器報錯
修改成p = &b後編譯通過,因爲這是修改指針p本身。
(二)int* const p
#include <stdio.h>
int main(void)
{
int a = 10;
int b = 20;
int* const p = &a;
*p = b;
return 0;
}
const在int*的右側,即指針本身爲常量,所以*p = b是允許的,而*p = &b是不允許的。
(三)const int* const p
通過一二的例子,舉一反三,可知兩個const分別出現在int *的左右側,說明p不僅指針本身不能修改,且p指向的內容也不能修改。