How to understand “typedef int (xxx)(int yyy);”?

2020-07-08 06:54发布

typedef int (xxx)(int yyy); seems to define a function pointer named xxx which points to a function with a integer parameter yyy.

But I can't understand that syntax...Could any one give a good explanation?


I find typedef int xxx(int yyy); still works. Any difference between them?

标签: c syntax
3条回答
孤傲高冷的网名
2楼-- · 2020-07-08 07:07

This defines a function type, not a function pointer type.

The pattern with typedef is that it modifies any declaration such that instead of declaring an object, it declares an alias to the type the object would have.

This is perfectly valid:

typedef int (xxx)(int yyy); // Note, yyy is just an unused identifier.
 // The parens around xxx are also optional and unused.

xxx func; // Declare a function

int func( int arg ) { // Define the function
    return arg;
}

The C and C++ languages specifically, and mercifully, disallow use of a typedef name as the entire type in a function definition.

查看更多
叛逆
3楼-- · 2020-07-08 07:19

If you have some declarator x in declaration T x, then T x(t1 p1, t2 p2) means function with params p1, p2, returning the same type as the declarator x was having before.

Parenthesis around the declarator means apply modifiers inside the parenthesis first.

In your case there are no modifiers inside the parenthesis. This means that there is no need in them.

Function prototype means There is a function somewhere that has this signature and its name is Blah.

Typedef with the prototype of the function means Lets give a name blah to a function signature. This does not imply that any function with this signature is existing. This name can be used as a type. For example:

typedef int xxx(int yyy);

xxx *func_ptr;       // Declaration of a variable that is a pointer to a function.
xxx *func2(int p1);  // Function that returns a pointer to a function.
查看更多
欢心
4楼-- · 2020-07-08 07:22

Yes, typedef int (xxx)(int yyy); is the same as typedef int xxx(int yyy); which defines a function type. You can find an example from page 156 C 11 standard draft N1570 . Quote from that page,

All three of the following declarations of the signal function specify exactly the same type, the first without making use of any typedef names.

    typedef void fv(int), (*pfv)(int);
    void (*signal(int, void (*)(int)))(int);
    fv *signal(int, fv *);
    pfv signal(int, pfv);
查看更多
登录 后发表回答