Home > other >  Unknown function signature in C
Unknown function signature in C

Time:05-29

I would be very thankful if you could explain me what the following means:

void bar(char *a, char *b, unsigned short c)      // (2)
{
    ...
}

void (*foo(void))(char *, char *, unsigned short) // (1)
{
    return bar;
}

In particular,

  • Why there are no variable names in (1)?
  • What does void (*foo(void)) mean? How can *foo(void) be a name?
  • What does return bar mean? Returns it the address of the bar source code, or the result from bar, or else?
  • Is there any feature in making these signatures so complicated?
  • Could you give an example of the usage?

CodePudding user response:

foo is a function that takes no arguments and returns a pointer to a function that takes three arguments of types char *, char * and unsigned short and returns void.

These declarations can be quite confusing because they should be read inside-out, bouncing left and right as needed:

  • foo is a thing ...
  • foo(void) ... apparently a function
  • *foo(void) ... whose return value can be dereferenced
  • (*foo(void))(...) ... and then called with these arguments
  • void (*foo(void))(...) ... which results in a value of type void.

You can also use cdecl.org to parse complex declarations for you:

declare foo as function (void) returning pointer to function (pointer to char, pointer to char, unsigned short) returning void

Usage examples:

// Immediately call the returned function.
// The similarity to the declaration is no coincidence!
(*foo())("hello", "world", 42);

// Store the returned function pointer for later invocation.
// This time there are no parentheses following the name, because
// this is a variable, not a function.
void (*fnPtr)(char *, char *, unsigned short) = foo();
(*fnPtr)("hello", "world", 42);

Argument names can always be omitted if the arguments aren't used inside the function. In this case, there isn't even a function body to use them in, because the body of foo isn't what the arguments are being passed to.

  • Related