以下说明了标题中三种具有迷惑性的指针的分辨方法和特征, 简单的分辨方法是: 从右往左读,遇到p就替换成“p is a ”遇到*就替换成“pointer to”
感谢如何理解常量指针与指针常量?问题下李鹏的回答
下面的代码严格遵守这种方法, 想复制源码可以移步github
#include <stdio.h>
int main()
{
/*
* int const p = 20; // p is a const int
* printf("p = %d\n", p);
*/
/*
* const int pi = 20;
* printf("pi = %d\n", pi);
*/
/*
* const int *p; // p is a pointer to int const, that is to say, *p is read-only
* int const d = 300;
* p = &d;
* printf("int const @p = %d\n", *p);
* int const f = 500;
* // *p = f; // read-only variable is not assignable
*/
/*
* int const *p; // p is a pointer to const int, that is to say, *p is read-only
* const int d = 300;
* p = &d;
* printf("int const @p = %d\n", *p);
* int const f = 500;
* // *p = f; // read-only variable is not assignable
*/
/*
* int d = 300;
* int *const p = &d; // p is a const pointer to int, that is to say, p is read-only but the value p points to is mutable
* printf("int @p = %d\n", *p);
* d = 500;
* printf("int @p = %d\n", *p);
* *p = 800;
* printf("int @p = %d\n", *p);
* printf("int d = %d\n", d);
*/
/**
* There is no const *int p;
*/
/*
* int const d = 300;
* const int *const p = &d; // p is a const pointer to int const, that is to say, p and *p are both read-only
* // p = &d; // cannot assign to variable 'p' with const-qualified type 'const int *const'
* printf("int const @ const pointer p is %d\n", *p);
*/
/*
* const int d = 300;
* int const *const p = &d; // p is a const pointer to const int
* // p = &d; // cannot assign to variable 'p' with const-qualified type 'const int *const'
* printf("const int @ const pointer p is %d\n", *p);
*/
}