const * and * const

对于int * const cpi,const修饰指针cpi本身,所以指针本身是常量不可变,而其所指之处的值可变。称为常量指针。
对于const int * pci 或 int const * pci,const修饰的是(*pci),所以pci是指向常量的指针。

 1 #include <stdio.h>
 2 
 3 int main() {
 4 
 5     int a = 10;
 6     int * const cpi = &a; // cpi is const, so cpi can NOT be changed, but (*cpi) can be changed.
 7     *cpi = 20;
 8     // cpi = 0x10000; // cpi can NOT be changed
 9 
10     int b = 100;
11     int const * pci = &b;   // pci is a pointer which points to a const
12     const int * pci2 = &b;
13     pci = 0x10000;  // pci can be changed
14     // *pci = 1;   // *pci can NOT be changed
15 
16     return 0;
17 }

 

posted @ 2024-07-24 20:38  hk416hasu  阅读(1)  评论(0编辑  收藏  举报