Reputation: 356
I want to be able to call multiple functions using a single generic function call.
Currently I am trying to implement something like this:
main()
{
generic();
}
A(){.....};
B(){.....};
C(){.....};
Where I call from main()
some generic function, which, in turn, is supposed to be able to call the functions: A(), B(), C().
How can I implement this in C?
Upvotes: 2
Views: 1901
Reputation: 1032
You can use function pointers, if all functions you want to call have same prototype.
Upvotes: 0
Reputation: 665
You have to use function pointers as below.
#include<stdio.h>
void A(void);
void B(void);
void C(void);
typedef void (*foo_ptr_t)( void );
foo_ptr_t foo_ptr_array[3]; //fucntion pointers of type foo_ptr_t
main()
{
int i = 0;
foo_ptr_array[0] = A; //assign function to each function pointer
foo_ptr_array[1] = B;
foo_ptr_array[2] = C;
for(i = 0; i<3; i++)
foo_ptr_array[i](); //call functions using function pointer
}
void A()
{
printf("We are in A\n");
}
void B()
{
printf("We are in B\n");
}
void C()
{
printf("We are in C\n");
}
Upvotes: 1
Reputation: 49
You can do it by using function pointers. Please refer on "how to use function pointers in C"
Upvotes: 2