简体   繁体   中英

Array of functions with built in arguments in C

Say I have these two functions and a definition of an array of these two functions:

int flag;

int add(int a, int b){
    return a+b;
}

int multiply(int a, int b){
    return a*b;
}

typedef int(*f)(int, int);
f func_array[2] = {&add, &multiply};

Now, there is a specific place in my code that I want to call these two functions depending on my flag state with the same arguments each time .

For example:

int var;
if(flag == 0)
{
    var = func_array[flag](1,1); 
}
else{
    var = func_array[flag](2,2); 
}

Is there a way to define it inside the array itself? Somwhow defining the array like this and just call the function:

f func_array[2] = {&add(1,1), &multiply(2,2)};
int var = func_array[flag]();

Is this a valid way? Is there any more elegant way to do it?

You can define a set of arrays for each parameter:

#define ARR_SIZE 2
typedef int(*f)(int, int);

f func_array[ARR_SIZE]     = {&add, &multiply};
int param1_array[ARR_SIZE] = { 1, 2};
int param2_array[ARR_SIZE] = { 1, 2};

The call would become

if(flag < ARR_SIZE)
{
    int var = func_array[flag](param1_array[flag], param2_array[flag]);
}

I just added a check on the array size.


With a macro

#define flag_call(flag) \
   func_array[flag](param1_array[flag], param2_array[flag])

you could simplify it even more

if(flag < ARR_SIZE)
{
    flag_call(flag);
}

Not sure what the point is but you can do this:

int add11(void){ return add(1,1); }
int multiply22(void){ return multiply(2,2); }
/*skipped the new typedef*/
int (*func_array2[2])(void) = {&add11,&multiply22};

https://godbolt.org/z/ejMn4n

The wrappers could even be inlinable if you make the array static or auto .

You can use a struct to bundle them together:

typedef int(*f)(int, int);

struct func_and_args {
    f func;
    int a;
    int b;
}

...

struct func_and_args arr[] = {{&add,1,1},{&multiply,2,2}};

int var = arr[flag].func(arr[flag].a,arr[flag].b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM