Union, Structs and the Soviet.

started by alice 21d ago

c
#include <stdio.h>


typedef struct
{
  char *leader;
  char *capital;
} Nation;

typedef struct
{
  char *plan_name;
  float time_left;
} Plan;

typedef struct
{
  Plan   five_plan;
  Nation republic;
} Union;

int
main (void)
{
  Union soviet;

  soviet.five_plan.time_left = 4.7f;
  soviet.five_plan.plan_name = "The great steelovertake";
  soviet.republic.leader     = "General Secretary";
  soviet.republic.capital    = "Moscow";

  printf ("Remaining: %.1f years\n", soviet.five_plan.time_left);
  printf ("What:      %s\n", soviet.five_plan.plan_name);
  printf ("Leader:    %s\n", soviet.republic.leader);
  printf ("Capital:   %s\n", soviet.republic.capital);

  return 0;
}

Here i use a struct named Union as union memory get overwritten, but then, why use unions instead of structs?
I cant see many cases where union would be better than just a struct.
That was all.
Bye!

On cases where alignment does not matter it is useful to use unions as well as to also use them in tagged variant where you would want a this or that version.

c
#include <stdio.h>


typedef struct {
  const char *plan_name;
  float time_left;
} plan_t;

typedef struct {
  const char *leader;
  const char *capital;
} nation_t;

typedef enum { KPLAN, KNATION } Kind;

typedef struct {
  Kind kind;
  union {
    plan_t  plan;
    nation_t  nation;
  } u;
} Record;

int main(void) {
  Record r1 = { .kind = KPLAN, .u.plan = { "The great steelovertake", 4.7f } };
  Record r2 = { .kind = KNATION, .u.nation = { "General Secretary", "Moscow" } };

  if (r1.kind == KPLAN) {
    printf("plan_t: %s, %.1f years left\n", r1.u.plan.plan_name, r1.u.plan.time_left);
  }
  if (r2.kind == KNATION) {
    printf("nation_t: %s, capital %s\n", r2.u.nation.leader, r2.u.nation.capital);
  }
}

Log in or register to reply.