C与C++中的函数与指针
用用就知道多厉害了,墙裂推荐这个将C语言声明翻译成口语的翻译器:C语言声明翻译器--在线版对表达式声明的理解float f,g;当对其求值时,表达式f和g的类型为浮点数类型(float)。float ((f));当对其求值时,表达式((f))的类型为浮点数类型(float)。float ff();表
用用就知道多厉害了,墙裂推荐这个将C语言声明翻译成口语的翻译器:C语言声明翻译器--在线版
对表达式声明的理解
float f,g;当对其求值时,表达式f和g的类型为浮点数类型(float)。 float ((f));当对其求值时,表达式((f))的类型为浮点数类型(float)。 float ff();表达式ff()求值结果是一个浮点数,也就是说,ff是一个返回值为浮点类型的函数。 float *pf;表达式*pf是一个浮点数,也就是说,pf是一个指向浮点数的指针。
float *g(), (*h)()()的优先级高于*,所以前者为float *(g());,即g是一个函数,该函数的返回值是一个指向浮点数的指针。所以,h是一个函数指针,返回值是一个浮点数。
(float (*)()) 类型转换符
int *f()==int *(f()) 函数调用操作符()的优先级高于间接访问操作符*。因此,f是一个函数,它的返回值类型是一个指向整型的指针。
int (*f)()
程序中的每个函数都位于内存中的某个位置,所以存在着指向那个位置的指针。
理解C语言声明的优先规则(自《C专家编程》)
| 序号 | 详情 |
|---|---|
| A | 声明从它的名字开始读取,然后按照优先级顺序依次读取。 |
| B | 优先级从高到低依次是: 1. 声明中被括号括起来的那部分 2. 后缀操作符:括号 ()表示这是一个函数,方括号[]表示为一个数组。3. 前缀操作符:星号*表示“指向...的指针” |
char * const *(*next)();
(*next)next是一个指针 2.(*next)()next是一个指针,指向一个函数。这个函数接受的参数为空。*(*next)()next是一个指针,指向一个函数。这个函数接受的参数为空,返回的参数为一个指针。char * const *(*next)()next是一个指针,指向一个函数。这个函数接受的参数为空,返回的参数为一个指针,它指向的对象是一个指向char的常量指针。 即:declare next as pointer to function returning pointer to const pointer to char
其它表达式
| 表达式 | 解析 |
|---|---|
char *(*c[10])(int **p); |
declare c as array 10 of pointer to function (pointer to pointer to int) returning pointer to char |
int (*(*foo)(void ))[3]; |
declare foo as pointer to function (void) returning pointer to array 3 of int |
int (*f)(int *, int (*)(int*)); |
declare f as pointer to function (pointer to int, pointer to function (pointer to int) returning int) returning int |
int (*f[5])(int *); |
declare f as array 5 of pointer to function (pointer to int) returning int |
int (*(*f)[5])(int *); |
declare f as pointer to array 5 of pointer to function (pointer to int) returning int |
int (*(*f)(int *))[5]; |
declare f as pointer to function (pointer to int) returning pointer to array 5 of int |
int (*(*f)[5][6])[7][8]; |
declare f as pointer to array 5 of array 6 of pointer to array 7 of array 8 of int |
int (*(*(*f)(int *))[5])(int *); |
declare f as pointer to function (pointer to int) returning pointer to array 5 of pointer to function (pointer to int) returning int |
int (*(*f[7][8][9])(int*))[5]; |
declare f as array 7 of array 8 of array 9 of pointer to function (pointer to int) returning pointer to array 5 of int |