Can a function prototype typedef be used in function definitions?

前端 未结 2 1322
日久生厌
日久生厌 2020-12-02 20:09

I have a series of functions with the same prototype, say

int func1(int a, int b) {
  // ...
}
int func2(int a, int b) {
  // ...
}
// ...

相关标签:
2条回答
  • 2020-12-02 20:50

    A typedef defines a type, not a header (which is source code text). You have to use #define (although I don't recommend it) if you need to factor out the code for the header.

    ([Edited] The reason the first one works is that it's not defining a prototype -- it's defining a variable of the type defined by the typedef, which isn't what you want.)

    0 讨论(0)
  • 2020-12-02 21:10

    You cannot define a function using a typedef for a function type. It's explicitly forbidden - refer to 6.9.1/2 and the associated footnote:

    The identifier declared in a function definition (which is the name of the function) shall have a function type, as specified by the declarator portion of the function definition.

    The intent is that the type category in a function definition cannot be inherited from a typedef:

    typedef int F(void); // type F is "function with no parameters
                         // returning int"
    F f, g; // f and g both have type compatible with F
    F f { /* ... */ } // WRONG: syntax/constraint error
    F g() { /* ... */ } // WRONG: declares that g returns a function
    int f(void) { /* ... */ } // RIGHT: f has type compatible with F
    int g() { /* ... */ } // RIGHT: g has type compatible with F
    F *e(void) { /* ... */ } // e returns a pointer to a function
    F *((e))(void) { /* ... */ } // same: parentheses irrelevant
    int (*fp)(void); // fp points to a function that has type F
    F *Fp; //Fp points to a function that has type F
    
    0 讨论(0)
提交回复
热议问题