6

I have a piece of code and I don't understand that one typedef:

typedef void (inst_cb_t) (const char*, size_t);

Doesn't that actually mean you can use inst_cb_t as a void now? But what about the stuff in the second brackets?

haccks
  • 104,019
  • 25
  • 176
  • 264
SimonH
  • 1,385
  • 15
  • 35
  • 1
    May find [this interesting](http://cdecl.ridiculousfish.com/?q=void+%28inst_cb_t%29+%28const+char*%2C+size_t%29%3B) – WhozCraig Feb 18 '15 at 15:35
  • No, that's a typedef for a function pointer. See http://stackoverflow.com/questions/1591361/understanding-typedefs-for-function-pointers-in-c-examples-hints-and-tips-ple – inetknght Feb 18 '15 at 15:35
  • 2
    @inetknght that's a typedef for a function, not for a function pointer. – mch Feb 18 '15 at 15:39

1 Answers1

12

The declaration

typedef void (inst_cb_t) (const char*, size_t);

defines inst_cb_t as a function that takes two arguments of type const char* and size_t and returns void.

One interesting part of this declaration is that you can use this only in function declaration and pointer to function deceleration.

inst_cb_t foo;  

You can't use it in function definition like

inst_cb_t foo      // WRONG
{
    // Function body
}  

Look at C standard:

C11: 6.9.1 Function definitions:

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

and footnote 162 is

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
haccks
  • 104,019
  • 25
  • 176
  • 264