喜闻乐见的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
", 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