OOC:en:3.8 Arithmetic

来自 ChinaUnix Wiki

If we want to do arithmetic, we let the execute functions return double values to be printed in process():

   static double exec (const void * tree) 
   { 
       return (* (struct Type **) tree) —> exec(tree); 
   } 
   void process (const void * tree) 
   { 
       printf("\t%g\n", exec(tree)); 
   } 

For each type of node we need one execution function which computes and returns the value for the node. Here are two examples:

   static double doVal (const void * tree) 
   { 
       return ((struct Val *) tree) —> value; 
   } 
   static double doAdd (const void * tree) 
   { 
       return exec(((struct Bin *) tree) —> left) + 
           exec(((struct Bin *) tree) —> right); 
   } 
   static struct Type _Add = { mkBin, doAdd, freeBin }; 
   static struct Type _Value = { mkVal, doVal, free }; 
   const void * Add = & _Add; 
   const void * Value = & _Value;
个主工具