home *** CD-ROM | disk | FTP | other *** search
/ Shareware Overload / ShartewareOverload.cdr / progm / ctutor2.zip / UNION2.C < prev    next >
Text File  |  1989-11-10  |  2KB  |  65 lines

  1.                                          /* Chapter 11 - Program 6 */
  2. #include "stdio.h"
  3. #define AUTO 1
  4. #define BOAT 2
  5. #define PLANE 3
  6. #define SHIP 4
  7.  
  8. void main()
  9. {
  10. struct automobile {  /* structure for an automobile         */
  11.    int tires;
  12.    int fenders;
  13.    int doors;
  14. };
  15.  
  16. typedef struct {     /* structure for a boat or ship        */
  17.    int displacement;
  18.    char length;
  19. } BOATDEF;
  20.  
  21. struct {
  22.    char vehicle;         /* what type of vehicle?           */
  23.    int weight;           /* gross weight of vehicle         */
  24.    union {               /* type-dependent data             */
  25.       struct automobile car;      /* part 1 of the union    */
  26.       BOATDEF boat;               /* part 2 of the union    */
  27.       struct {
  28.          char engines;
  29.          int wingspan;
  30.       } airplane;                 /* part 3 of the union    */
  31.       BOATDEF ship;               /* part 4 of the union    */
  32.    } vehicle_type;
  33.    int value;            /* value of vehicle in dollars     */
  34.    char owner[32];       /* owners name                     */
  35. } ford, sun_fish, piper_cub;   /* three variable structures */
  36.  
  37.        /* define a few of the fields as an illustration     */
  38.  
  39.    ford.vehicle = AUTO;
  40.    ford.weight = 2742;              /* with a full gas tank */
  41.    ford.vehicle_type.car.tires = 5;  /* including the spare */
  42.    ford.vehicle_type.car.doors = 2;
  43.  
  44.    sun_fish.value = 3742;           /* trailer not included */
  45.    sun_fish.vehicle_type.boat.length = 20;
  46.  
  47.    piper_cub.vehicle = PLANE;
  48.    piper_cub.vehicle_type.airplane.wingspan = 27;
  49.  
  50.    if (ford.vehicle == AUTO) /* which it is in this case */
  51.       printf("The ford has %d tires.\n",ford.vehicle_type.car.tires);
  52.  
  53.    if (piper_cub.vehicle == AUTO) /* which it is not in this case */
  54.       printf("The plane has %d tires.\n",piper_cub.vehicle_type.
  55.              car.tires);
  56. }
  57.  
  58.  
  59.  
  60. /* Result of execution
  61.  
  62. The ford has 5 tires.
  63.  
  64. */
  65.