1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <stdio.h>
#include <string.h>
#ifndef ARRAYSIZE
#define ARRAYSIZE(x) (sizeof(x)/sizeof(x[0]))
#endif
typedef int (*FONCTION)(int);
struct st_fonc
{
char const *nom;
FONCTION fonc;
};
int AppelFonction(struct st_fonc const *table, size_t taille, char const *nom, int param)
{
int ret = 0;
size_t i;
//Rechercher.
//On peut faire plus compliqué (recherche triée, hachage, etc.)
//mais c'est un exemple.
for(i=0 ; i<taille ; i++)
{
if(strcmp(nom, table[i].nom)==0)
break; /* trouvé! */
}
if(i<taille)
{
FONCTION fonc = table[i].fonc;
ret = fonc(param);
}
return ret;
}
int foncMul(int);
int foncDiv(int);
/* main() retourne TOUJOURS un int */
int main(void)
{
struct st_fonc tableFonc[] = {
{"mul", foncMul},
{"div", foncDiv}
/*etc.*/
};
/* ... */
/* TEST */
{
int a = 42;
char const * nom = "mul";
int b = AppelFonction(tableFonc, ARRAYSIZE(tableFonc), nom, a);
printf("b=%d\n", b);
}
return 0;
} |
Partager