最近在翻看stackoverflow
时看到了一篇文章[2],主要介绍了const int*, const int * const, int const
的区别,排名第一的答案中引用了一种叫Clockwise/Spiral Rule
的技巧(David Anderson于1994年05月06日写的一篇博客),笔者仔细看了下,感觉这个方法非常棒,有必要给各位同学分享一下。
通过阅读本文,编程者可以很方便地搞清楚C/C++
变量或者函数声明。
Step 1. 从未知的变量开始,以“螺旋状+顺时针”方向移动,当遇到以下内容时,用相应的英文语句来代替它们:
[X] or []
=> Array X size of... or Array undefined size of...
(type1, type2)
=> function passing type1 and type2 returning...
*
=> pointer(s) to...
Step 2. 重复Step 1,直到所有的符号都被遍历;
Step 3. 一定要先解决括号里的东西!
+-------+
| +-+ |
| ^ | |
char *str[10];
^ ^ | |
| +---+ |
+-----------+
首先问自己的一个问题:str
是什么玩意?
str is an ...
str
开始,以螺旋式顺时针方向移动,看到的第一个字符是[
,所以,这意味着这里有一个数组,所以...str is an array 10 of...
*
,所以,这意味着这里有个指针,所以...str is an array 10 of pointers to...
;
),继续前进得到了char
类型,所以...str is an array 10 of pointers to char
+--------------------+
| +---+ |
| |+-+| |
| |^ || |
char *(*fp)( int, float *);
^ ^ ^ || |
| | +--+| |
| +-----+ |
+------------------------+
首先问自己的一个问题:fp
是什么玩意?
fp is a ...
fp
开始,以螺旋式顺时针方向移动,看到的第一个字符是)
,因此fp
在括号内,所以在括号内继续螺旋式移动,看到的下一个字符是*
,所以...fp is a pointer to...
(
;因此,我们遇到了一个函数,所以...fp is a pointer to a function passing an int and a pointer to float returning...
*
字符,所以...fp is a pointer to a function passing an int and a pointer to float returning a pointer to...
;
,但还没有访问所有的符号,所以继续,最后到了char
类型,所以...fp is a pointer to a function passing an int and a pointer to float returning a pointer to char
+-----------------------------+
| +---+ |
| +---+ |+-+| |
| ^ | |^ || |
void (*signal(int, void (*fp)(int)))(int);
^ ^ | ^ ^ || |
| +------+ | +--+| |
| +--------+ |
+----------------------------------+
首先问自己的一个问题:signal
是什么玩意?(注意,变量signal
在括号内,所以我们必须先搞定它)
signal is a ...
(
,所以有...signal is a function passing an int and a ...
fp
使用同样的规则,所以...fp是什么玩意?fp
也在小括号内,所以继续,我们看到一个*
,所以...fp is a pointer to...
(
,所以我们知道遇到了函数...fp is a pointer to a function passing int returning...
void
,所以...fp is a pointer to a function passing int returning nothing(void)
signal
,我们现在有...signal is a function passing an int and a pointer to a function passing int returning nothing(void)
*
,所以...signal is a function passing an int and a pointer to a function passing int returning nothing returning a pointer to...
(
,我们知道遇到了函数,所以....signal is a function passing an int and a pointer to a function passing int returning nothing returning a pointer to a function passing int returning...
void
,所以signal
的最终完整定义是...signal is a function passing an int and a pointer to a function passing int returning nothing returning a pointer to a function passing int returning nothing(void)
这个规则同样适用于const
以及 volatile
,例如:
const char *ptr;
ptr is a pointer to a char constant (ptr 是指向 const char 的指针,即ptr指向的值不可改变,但是指针可以改变)
char const *ptr;
ptr is a pointer to a constant char
所以 const char *ptr
与 char const * ptr
表示一个意思[2]。
char * const ptr;
ptr is a constant pointer to char (ptr 是一个const指针指向char,即ptr不可改变,但是指针指向的内容可以改变)
volatile char * const ptr;
ptr is a constant pointer to char volatile