CKTIS / C
EmpCmp : un tableau de pointeurs vers des fonctions de comparaison en C
Définissez un type pointeur vers une fonction de comparaison d’employés et appelez indirectement les quatre fonctions actives d’un tableau de huit éléments.
Version : ISO C23; implementation support may vary
Syntaxe
typedef struct Employee Employee;
typedef int (*EmpCmp)(const Employee *, const Employee *);
/* With the four compatible functions already declared: */
EmpCmp comparators[8] = {by_id, by_department, by_salary, by_years};EmpCmp est un nom défini par typedef pour un pointeur vers une fonction qui reçoit deux arguments de type const Employee * et renvoie un int. C’est un alias du type pointeur, pas une fonction ni un nouveau type distinct. Les parenthèses autour de *EmpCmp indiquent qu’il s’agit d’un pointeur vers une fonction.
EmpCmp comparators[8] est un tableau de huit pointeurs vers des fonctions. Dans cet initialiseur, chaque nom de fonction compatible est converti en pointeur vers cette fonction. Les indices 0 à 3 contiennent les quatre pointeurs actifs. Les éléments omis, d’indices 4 à 7, sont initialisés avec des pointeurs nuls. La capacité du tableau n’est pas le nombre d’entrées actives.
comparators[i](&a, &b) appelle indirectement la fonction sélectionnée par i. La forme explicite équivalente est (*comparators[i])(&a, &b). Utilisez un indice valide et n’appelez que des fonctions compatibles via des pointeurs non nuls. Un appel via un pointeur nul ou un pointeur vers un type de fonction incompatible entraîne un comportement indéfini. Une conversion de type explicite ne rend pas sûr un appel incompatible.
Par convention ici, un résultat négatif indique que a précède b, zéro indique une égalité sur le champ choisi et un résultat positif indique que a suit b. Le type EmpCmp fixe la signature, mais n’impose pas cette convention. Cette technique ne requiert aucune fonctionnalité introduite par C23 ; la prise en charge de C23 dépend de l’implémentation.
Exemples
#include <stdio.h>
typedef struct Employee {
int id;
int department;
int salary;
int years;
} Employee;
typedef int (*EmpCmp)(const Employee *, const Employee *);
static int cmp_int(int a, int b)
{
return (a > b) - (a < b);
}
static int by_id(const Employee *a, const Employee *b)
{
return cmp_int(a->id, b->id);
}
static int by_department(const Employee *a, const Employee *b)
{
return cmp_int(a->department, b->department);
}
static int by_salary(const Employee *a, const Employee *b)
{
return cmp_int(a->salary, b->salary);
}
static int by_years(const Employee *a, const Employee *b)
{
return cmp_int(a->years, b->years);
}
int main(void)
{
const Employee a = {101, 2, 7000, 5};
const Employee b = {102, 2, 6500, 8};
enum { active_count = 4 };
EmpCmp comparators[8] = {by_id, by_department, by_salary, by_years};
const char *const labels[active_count] = {"id", "department", "salary", "years"};
for (int i = 0; i < active_count; ++i) {
printf("%s: %d\n", labels[i], comparators[i](&a, &b));
}
return 0;
}
Résultat
id: -1 department: 0 salary: 1 years: -1
La boucle compare les deux mêmes enregistrements selon quatre critères, sans les trier. `department: 0` signifie seulement que les deux employés ont le même numéro de service.
Leçons associées
- C · Leçon 55 · Intermédiaire · Version : 3