我如何读取“int(* functionFactory(int n))(int,int){...}”?

时间:2014-03-07 01:46:23

标签: c

这是一个语法问题。我强调我想理解如何阅读下面的代码。

我在尝试理解以下代码(1)如何转换为其下的代码(2)时遇到了巨大的麻烦:

Code Zero:

int addInt(int n, int m) {
    return n+m;
}

代码一:

// this is a function called functionFactory which receives parameter n
// and returns a pointer to another function which receives two ints
// and it returns another int
int (*functionFactory(int n))(int, int) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}

代码二:

typedef int (*myFuncDef)(int, int);
// note that the typedef name is indeed myFuncDef

myFuncDef functionFactory(int n) {
    printf("Got parameter %d", n);
    myFuncDef functionPtr = &addInt;
    return functionPtr;
}

我正在努力争取两件事,这就是原因。我已将上面的代码修改为我认为它们应该是什么样的。

没有Typedef的显式函数定义(应与标题相同:

代码4:

int (*myFuncDef)(int, int) functionFactory(int n) {
    printf("Got parameter %d", n);
    int (*functionPtr)(int,int) = &addInt;
    return functionPtr;
}

代码5: typedef本身(用于简化代码2):

typedef int (*myFuncDef)(int, int) myFuncDef;

请注意,这些规定了基本规则:返回类型,标识符,参数。

我真的很感激我可以阅读有关这一切如何运作的严格规则的链接。概述说明会很棒,因为spec不像课程那样提供“教程”。 非常感谢你!

[编辑]此外,

请注意,这些摘录自:How do function pointers in C work?

2 个答案:

答案 0 :(得分:4)

int (*functionFactory(int n))(int, int) { … }?

Remember these rules for C declares
And precedence never will be in doubt
Start with the Suffix, Proceed with the Prefix
And read both sets from the inside out

(当然,除非parens说“先做这个”。)

所以:functionFactory是

[open paren] 
[suffix (int n)]     a function taking an `int` argument called `n` that returns
[prefix *]           a pointer to
[close paren]
[suffix (int, int)]  a function taking two `int` arguments and returning
[prefix int]         an integer

,跟随它的{...}给出了functionFactory行为的定义。

(我们可能从名称functionFactory猜测它将返回一个指向函数的指针。我们也可以查看它的逻辑以查看它返回的类型。)

Typedef使用与变量声明完全相同的语法,新类型名称替换变量名称,当然还有typedef关键字替换它们。此工厂返回的类型的函数指针将具有类型

int (*functionFromFactory)(int,int); /* oops, forgot parens the first time */

所以这种指针的typedef将是

typedef int (*PtrToFunctionFromFactory)(int,int);

请注意,一旦您拥有该类型,functionFactory的声明可以简化为

PtrToFunctionFromFactory functionFactory(int n) {...}

(可能这个函数类比“工厂函数”更好的名称,并且该名称确实应该在typedef和工厂方法的名称中使用,但是因为你没有给我们任何东西更好地与我合作我很难接受过于抽象的名字。)

希望有所帮助。

答案 1 :(得分:1)

“从里到外,从右到左。”

从声明的名称,在该级别从右到左是“函数接受一个int返回一个指针...”,从一个级别“...到一个函数采用两个int返回一个int”。

相关问题