All pastes #1534557 Raw Edit

DrMax

public c v1 · immutable
#1534557 ·published 2009-08-19 01:24 UTC
rendered paste body
include <stdio.h>typedef void (*fonction_t)(int);void fonction1(int bidon) { printf("%s\n",__PRETTY_FUNCTION__); }void fonction2(int bidon) { printf("%s\n",__PRETTY_FUNCTION__); }void fonction3(int bidon) { printf("%s\n",__PRETTY_FUNCTION__); }typedef struct {  const char * commande;  fonction_t fonction;} commande_t;commande_t commandes[]= {  // triees!  {"bong",fonction1},  {"bonjour",fonction1},  {"floc",fonction3},  {"ninja",fonction3},  {"ping",fonction2},  {"plop",fonction1},  {"salut",fonction2},  {"smoke",fonction2},  {"zonk",fonction3},    {0,0}, };void call_back(const char * cette_commande) {  int i=0;  while (commandes[i].commande)   {    if (strcmp(commandes[i].commande,cette_commande)==0)     {      commandes[i].fonction(3);      return; // on a fini!     }    else i++;   }  printf("commande inconnue!!1!\n"); }void binary_call_back( const char * cette_commande, int max_commandes ) {  // on suppose qu'on connait   // le maximum deja!  int bas=0;  int haut=max_commandes;  // a chaque iteration on  // choisit une motie de l'intervalle  // courant jusqu'a ce que l'on ait  // un interval "degenere"  //  while (bas<haut)   {    int milieu=(bas+haut)/2;    int r=strcmp(cette_commande,commandes[milieu].commande);    // 3 cas:    if (r<0)     // alors c'est l'intervalle du bas     haut = milieu-1;    else if (r>0)     // alors c'est l'intervalle du haut     bas=milieu+1;    else     // sinon, r=0, on a trouve!     {      commandes[milieu].fonction(5);      return; // fini!     }   }  // si on arrive ici, c'est que la commande  // n'existe pas!  printf("commande inconnue, zutte.\n"); }int main() {  call_back("ninja");  call_back("salut");  call_back("zigzig");  binary_call_back("plop",9);  binary_call_back("floc",9);  binary_call_back("zigzig",9); }