Home Segments Index Top Previous Next

432: Mainline

Once you have introduced enumeration constants, you can improve the clarity of the switch statement by replacing the integers with those enumeration constants. Such replacement is illustrated in the following revised version of the analyze_trades program:

#include   
/* Define the trade apparatus */ 
struct trade {double price; int number;}; 
double trade_price (struct trade *x) {return x -> price * x -> number;} 
/* Define enumeration constants, needed in switch statement */ 
enum {food, trucking, computers, metals, health, airline}; 
/* Define trade array */ 
struct trade *trade_pointers[100]; 
main ( ) { 
  /* Declare various variables */ 
  int limit, counter, industry, number; 
  double price, sum = 0.0; 
  /* Read trade information and compute cost */ 
  for (limit = 0; 3 == scanf ("%i%lf%i", &industry, &price, &number);) 
    switch (industry) { 
      case trucking: case airline: 
        trade_pointers[limit]  
          = (struct trade*) malloc (sizeof (struct trade)); 
        trade_pointers[limit] -> price = price; 
        trade_pointers[limit] -> number = number; 
        ++limit; 
        break; 
      case food: case computers: case metals: case health: 
        break; 
      default: printf ("Industry code %i is unknown!\n", industry);  
               exit (0); 
    } 
  for (counter = 0; counter < limit; ++counter) 
    sum = sum + trade_price (trade_pointers[counter]); 
  printf ("The total cost of %i selected trades is %f.\n", 
                             limit,                sum); 
} 
--- Data ---
0  3.3  300 
1  2.5  400 
5  9.9  100 
5 10.1  100 
2  5.0  200 
--- Result --- 
The total cost of 3 selected trades is 3000.000000.