C
Chad
#include <stdio.h>
enum Type {DAYS, HOURSMINUTES};
struct Days {
int num_days;
};
struct HoursMinutes {
int num_hours;
int num_minutes;
};
struct Time {
enum Type tag;
union {
struct Days days;
struct HoursMinutes hm;
} u;
};
void print(struct Time ti)
{
int minutes;
if (ti.tag == DAYS) {
minutes = ti.u.days.num_days * 24 * 60;
}
else {
minutes = ti.u.hm.num_hours *
60 + ti.u.hm.num_minutes;
}
printf("number of minutes = %d\n", minutes);
}
int main(void)
{
struct Time ti;
ti.tag = DAYS;
ti.u.days.num_days = 10;
print(ti);
ti.tag = HOURSMINUTES;
ti.u.hm.num_hours = 15;
ti.u.hm.num_minutes = 59;
print(ti);
}
1)Is 'struct Time' a dynamic structure in this case?
2)I'm assuming this
struct Time {
enum Type tag;
union {
struct Days days;
struct HoursMinutes hm;
} u;
};
Is some kind of tagged union. I don't see why the author constucted
the structure in this way.
Chad
enum Type {DAYS, HOURSMINUTES};
struct Days {
int num_days;
};
struct HoursMinutes {
int num_hours;
int num_minutes;
};
struct Time {
enum Type tag;
union {
struct Days days;
struct HoursMinutes hm;
} u;
};
void print(struct Time ti)
{
int minutes;
if (ti.tag == DAYS) {
minutes = ti.u.days.num_days * 24 * 60;
}
else {
minutes = ti.u.hm.num_hours *
60 + ti.u.hm.num_minutes;
}
printf("number of minutes = %d\n", minutes);
}
int main(void)
{
struct Time ti;
ti.tag = DAYS;
ti.u.days.num_days = 10;
print(ti);
ti.tag = HOURSMINUTES;
ti.u.hm.num_hours = 15;
ti.u.hm.num_minutes = 59;
print(ti);
}
1)Is 'struct Time' a dynamic structure in this case?
2)I'm assuming this
struct Time {
enum Type tag;
union {
struct Days days;
struct HoursMinutes hm;
} u;
};
Is some kind of tagged union. I don't see why the author constucted
the structure in this way.
Chad