Domanda

I have a couple of question. I need to write a struct that will include a field that will be either empty or of some specific type, using union. which one it is should be decided by the value of a bool variable (inRoom in this case). so this is what I have:

typedef struct{}Unit;
typedef struct{
     Suspect currentPlayer;
     Dice dice;
     Bool inRoom;
     union{
         Suggestion suggestion;
         Unit suggestion; 
     }
 }Turn;

now, I understand that it's up to the programmer to know which type he's supposed to use. does that mean that this is not something I can put in the declaration of the struct, but rather in the program itself? is this the right way to define the union?

second question: in pascal I can define a variable that only hold a range of numbers

Dice=2..12;

how do I convert this to C language? I can use enum:

 typedef enum{2,3,4,5,6,7,8,9,10,11,12}

but won't that cause problems with any kind of arithmetics I'll try to do? is there a better way to define ranged variables in C?

È stato utile?

Soluzione

For the first question, the actual code should read the appropriate bool, and parse the appropriate member of the union. Note that this means you cannot name the two members of the union the same, because then you cannot differentiate them.

Thus, you should change:

     Suggestion suggestion;
     Unit suggestion; 

to something like

     Suggestion suggestion;
     Unit unit; 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top