In-Class Practice

Union Types



What is the output of the following program:


 /* Union Types - Handout
  * Counter.c
  * May 22 2006
  */

 #include <stdio.h>

 enum hand {minute, hour};

 typedef struct {
     enum hand timer;
     union {
         int m;
         struct {
             int h;
             int m;
         } hourly;
     } time;
 } Counter;

 void tick(Counter* t) {

     switch(t->timer) {
     case minute: (t->time.m)++; break;
     case hour:   (t->time.hourly.m)++;
                  if (t->time.hourly.m == 60) {
                      (t->time.hourly.h)++;
                      t->time.hourly.m = 0;
                      if (t->time.hourly.h == 24)
                          t->time.hourly.h = 0;
                  }
                  break;
     }
 }

 void display(const Counter *t) {

     switch(t->timer) {
     case minute:
         printf("%05d\n", t->time.m);
         break;
     case hour:
         printf("%02d:%02d\n", t->time.hourly.h, t->time.hourly.m); 
         break;
     }
 }

 int main(void) {
     int i;
     Counter stopwatch, clock;

     stopwatch.timer = minute;
     stopwatch.time.m = 0;
     clock.timer = hour;
     clock.time.hourly.h = 23;
     clock.time.hourly.m = 58;
     for (i = 0; i < 3; i++) {
         tick(&stopwatch);
         tick(&clock);
         display(&stopwatch);
         display(&clock);
     }

     return 0;
 }

Show your output below:

















   Printer Friendly Version of this Page print this page     Top  Go Back to the Top of this Page



  Designed by Chris Szalwinski   Copying From This Site