Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typedef function and is it useful? [duplicate]

I'm studying in-depths of languages, so I can understand what's happening in code, rather than print some things and watch and see what happens.

Recently, in search for better implementation for class function table I found myself stumbled upon this C language standard: http://www.iso-9899.info/wiki/Typedef_Function_Type

I've tried it out and it seems working feature:

typedef void fnr(int x);

main()
{
    fnr t;
}

This seemed a glorious day for me searching the way to pack up functions into my structure, until I realized, that fnr t; is not as useful as I had intended. It can neither be assigned, nor used the proper way I wished it to be (probably lambda for C-users). It does not even exist in disassembly!

What does this language feature do? What can it be used for besides simplifying function pointers?

like image 345
Ilya Pakhmutov Avatar asked Nov 30 '25 04:11

Ilya Pakhmutov


1 Answers

You've declared fnr as a function type. While a function type cannot be assigned to, a pointer to a function type can. For example:

typedef void fnr(int x);

void f(int x)
{
    printf("x=%d\n", x);
}

int main()
{
    fnr *t = f;
    t(1);
}

You could also define the typedef as a function pointer:

typedef void (*fnr)(int x);
...
fnr t = f;

Using a typedef for a function pointer is most useful when a function pointer is either passed to or returned from a function. As an example, let's look at the signal function which does both:

  typedef void (*sighandler_t)(int);

  sighandler_t signal(int signum, sighandler_t handler);

The second parameter to this function is a pointer to a signal handling function, and it also returns a pointer to a signal handling function. Without the typedef, it would look like this:

void (*signal(int signum, void (*handler)(int)))(int)
like image 101
dbush Avatar answered Dec 02 '25 21:12

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!