Using a loop to call 'sequentially' named functions in C

  • A+

Say I have functions foo_1(), foo_2(),...foo_n()

How could I use a loop to call them, that is how could 'convert' a string to a function call:

for (i = 0; i < n; i++)     switch (fork()) {         case 0:         //child process             *COMVAR+=m;             //call foo_i()             exit(4);         case -1:             exit(5);    } 



The best you can do involves an array of function pointers

#include <stdio.h>  typedef int (*fx)(void); // fx is pointer to function taking no parameters and returning int  int foo_1(void) { printf("%s/n", __func__); return 1; } int foo_2(void) { printf("%s/n", __func__); return 2; } int foo_three(void) { printf("%s/n", __func__); return 3; }  int main(void) {     fx foo[3] = { foo_1, foo_2, foo_three };     for (int k = 0; k < 3; k++) {         printf("foo[%d]() returns %d/n", k, foo[k]());     } } 

see code running on ideone


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: