喜闻乐见的const int *p、int* const p、const int* const p
生活随笔
收集整理的這篇文章主要介紹了
喜闻乐见的const int *p、int* const p、const int* const p
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
不廢話直接代碼示例:
1 void f(const int *p) { 2 3 int b = 10; 4 5 *p = 10; // error 6 7 p = &b; // fine 8 9 } 10 11 void f(int* const p) { 12 13 int b = 10; 14 15 *p = 10; // fine 16 17 p = &b; // error 18 19 } 20 21 void f(const int* const p) { 22 23 int b = 10; 24 25 *p = 10; // error 26 27 p = &b; // error 28 29 }
然而,如果function f使用了const作為承諾(不修改p或者不修改p指向的區域或者二者都有),function g與f有同樣的interface但g沒有使用const作任何承諾,如果f把p傳遞給了g,f是不會對g的行為做任何保證的(也就是說即便g對p或者p指向的區域做出了修改,編譯器仍然不會報錯,這是合理的,因為f只保證自己不會直接修改,但不保證自己調用的其他function不作修改)
下面是個示例:
1 #include <stdio.h> 2 3 void f(); 4 void g(); 5 6 7 int main() { 8 int a = 0; 9 int *p = &a; 10 f(p); 11 printf("a=%d\n", a); 12 return 0; 13 } 14 15 void f(const int *p) { 16 //*p = 10; // error 17 g(p); 18 } 19 20 void g(int *p) { 21 *p = 999; 22 }
?
轉載于:https://www.cnblogs.com/qrlozte/p/4019209.html
總結
以上是生活随笔為你收集整理的喜闻乐见的const int *p、int* const p、const int* const p的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 冰晶凤凰可以好友互赠吗 ; 急急急
- 下一篇: 听雪落下的声音是什么歌啊?