右左法则

本文介绍了一种名为“右左法则”的方法,用于帮助理解和解析复杂C/C++类型的声明。通过具体的例子展示了如何从最内层的括号开始,先向右读取再向左读取,遇到括号则改变方向,最终将复杂的声明拆解为易于理解的形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The right-left rule
Start reading the declaration from the innermost parentheses, go right, and then go left. When you encounter parentheses, the direction should be reversed. Once everything in the parentheses has been parsed, jump out of it. Continue till the whole declaration has been parsed.
One small change to the right-left rule: When you start reading the declaration for the first time, you have to start from the identifier, and not the innermost parentheses.
右左法则
法则运用如下:从最内部的括号开始阅读声明,向右看,然后向左看。当你碰到一个括号时就调转阅读的方向。括号内的所有内容都分析完毕就跳出括号的范围。这样继续,直到整个声明都被分析完毕。
对上述“右左法则”做一个小小的修正:当你第一次开始阅读声明的时候,你必须从变量名开始,而不是从最内部的括号。

1.
int (*ff(int)) (int *,int);
//等价于
typedef int (*pf)(int *,int);
pf ff(int);

2.
int (*Register (int (*pf)(const char *, const char *))) (const char *, const char *)
//等价于
typedef int (*pf)(const char *, const char *);
pf Register(pf);

3.
int * (* (*fp1) (int) ) [10];
//等价于
typedef int* (*pf)[10];
typedef pf (*fp)(int);
fp fp1;


4.
int *( *( *arr[5])())();
//等价于
typedef int* (*fp)();
typedef fp (*fp1)();
fp1 (*arr)[5];

5.
float ( *( *b())[] )();
//等价于
typedef float (*pf)();
typedef pf (*parr)[];
parr b();

6.
void * ( *c) ( char, int (*)());
//等价于
typedef int (*pf)()
typedef void* (*pf1)(char,pf);
pf1 c;

7.
void ** (*d) (int &, char **(*)(char *, char **));
//等价于
typedef char** (*pf)(char *, char **);
typedef void** (*pf1) (int &, pf);
pf1 d;

8.
float ( * ( * e[10])(int &) ) [5];
//等价于
typedef float (*parr)[5];
typedef parr (*pf)(int &);
pf e[10];

9.
double (*)()(*e)[9];
//等价于
typedef double (*pf)();
pf (*e)[9];

10.
int*(*a[5])(int,char *);
//等价于
typedef int* (*pf)(int,char *);
pf a[5];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值