Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a function pointer without a typedef

Tags:

c

I'm trying to write a function that returns a function pointer without using any typedefs. The returned function needs to be assignable to

static int (*compare_function)(int a);

Is this the best/only way to do it?

static static int (*compare_function)(int a)
assign_compare_function(int a,...,char* z){
//blah
}

There are two statics because I want the assigner function to be static as well.

like image 416
Elliot Gorokhovsky Avatar asked Oct 17 '25 06:10

Elliot Gorokhovsky


2 Answers

The first problem problem with your definition is that it makes zero sense to write static static. This is because static is a storage qualifier and it's not part of the type per se. The second problem is that you need a parameter list for both functions.

You can write this:

int (*compare_function(void))(int a) {
    ...
}

Or you can make compare_function static:

static int (*compare_function(void))(int a) {
    ...
}

Either of these will return an object of type int (*)(int a) which is what you want. To clarify, without using typedef, this is the only way to write a function that returns a function (not counting someo

Writing static static makes no sense. Imagine writing something like:

// no
typedef static int SInt;

That just doesn't make any sense either, so when you have a variable:

static int (*compare_function)(int a);

The type is int (*)(int), and the storage duration is static, and the linkage is internal.

like image 130
Dietrich Epp Avatar answered Oct 19 '25 21:10

Dietrich Epp


Here is the way to correctly return function pointer:

int compare_function(int a);

int (*assign_compare_function())(int)
{
  return compare_function;
}
like image 44
Michal Krzyz Avatar answered Oct 19 '25 20:10

Michal Krzyz



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!