Sayalic
Sayalic

Reputation: 7650

How to understand "typedef int (xxx)(int yyy);"?

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?

Upvotes: 8

Views: 1800

Answers (3)

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

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.

Upvotes: 0

CS Pei
CS Pei

Reputation: 11047

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);

Upvotes: 0

Potatoswatter
Potatoswatter

Reputation: 137870

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.

Upvotes: 15

Related Questions