1)const int *pp是一個指向整型常量的指標,可以修改指標的值,但不能修改指標所指向的值#include <stdio.h>int main(){ int b = 5; int c = 3; const int *p = &b; printf("*p is %d\n",*p); *p = 6;//錯誤,向唯讀位置 *p賦值 p = &c;//可以修改指標的值 printf("*p is %d\n",*p); return 0;}
2)int const * p和1)中的用法相同,p是一個指向整型常量的指標
3)int * const p;p是一個常指標,指標p是常量,它的值無法修改,但p指向的整型的值可以修改#include <stdio.h>int main(){ int b = 5; int c = 3; int * const p = &b; printf("*p is %d\n",*p); *p = 6;//正確 p = &c;//錯誤,向唯讀變數p賦值 printf("*p is %d\n",*p); return 0;}
4)const int * const p無論指標本身還是它所指向的值都是常量,不能修改#include <stdio.h>int main(){ int b = 5; int c = 3; const int * const p = &b; printf("*p is %d\n",*p); *p = 6;//錯誤,向唯讀位置 *p賦值 p = &c;//錯誤,向唯讀變數p賦值 printf("*p is %d\n",*p); return 0;}
簡單的辨別這幾種用法的判斷方法
沿著*號一條線,如果const位於*左側,那麼const就是用來修飾指標所指向的變數,即指標指向常量;
如果const位於*右側,那麼const就是用來修飾指標本身,即指標本身是常量。
這樣是不是很好的就知道了const到底修飾誰了呢?大家也可以試試哈 ^_^