ZioByte
ZioByte

Reputation: 2994

Is it possible to use a typedef for function DEFINITION?

I am routinely using typedefs for type and function declaration.

Question is: is it possible to define a function having a previously declared type (i.e.: signature)?

I mean: given the well known declaration:

void (*signal(int sig, void (*func)(int)))(int);

or, better, it's (clearer) equivalent:

typedef void SigCatcher(int);
SigCatcher *signal(int sig, SigCatcher *func);

how is it possible to define a SigCatcher function?

of course I can define:

void my_sig_catcher(int sig, SigCatcher *func) {
    ...
}

but that doesn't make evident this is really a SigCatcher. What I would like is something like:

SigCatcher my_sig_catcher {
    ...
}

but this is not a valid construct.

Is there some (not too contrived) way to achieve this?

Upvotes: 1

Views: 70

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

It's not possible. It's not possible, because the language grammar disallows it. The C standard even explicitly states, that it has the intent of disallowing such function definitions in footnote 162 mentioned in 6.9.1p2. I copied the footnote below in the hopes it will clears things up:

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

What's interesting, it's allowed for function declarations. So the following is possible:

SigCatcher my_sig_catcher;

But the definition has to be:

void SigCatcher(int some_name) { /*...*/ }

Upvotes: 1

Related Questions