Use of Enum within a Struct

Asked

Viewed 166 times

0

Good evening. I have to do a program where I have to create several elements using the following:

typedef enum {ATRIB, ADD, SUB, MUL, IF_I, PRINT, READ, GOTO_I, LABEL} OpKind;

typedef enum {EMPTY, INT_CONST, STRING} ElemKind;

typedef struct{
     ElemKind kind;
      union{ 
        int val;
        char *name;
        } contents;
} Elem;

typedef struct{
   OpKind op;
   Elem first, second, third;
} Instr;

However, I am failing to see how to assign values to each of the elements of Instr. Can anyone give a simple example of how I can do the assignment? Thank you

  • Something like: Instr.first.Kind = EMPTY;

  • Thanks made it clear

1 answer

0


Instr is a guy. You have to define a object (a variable) of this type to assign a value.

Instr foo; // foo não inicializado
Instr bar = {0}; // bar inicializado com zeros
Instr baz = {ATTRIB, {EMPTY, {0}}, {INT_CONST, {42}}, {STRING, {-1}}};
Instr quux = { .op = READ }; // C99 designated initializer

foo.second.contents.name = "foo"; // atribuição
  • Thank you for the examples it has already become clearer how to assign values

Browser other questions tagged

You are not signed in. Login or sign up in order to post.