0

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?

timrau
  • 22,578
  • 4
  • 51
  • 64
littlerunaway
  • 443
  • 2
  • 8
  • 18
  • 1
    I'd use simply the int type by taking care that the value is always between 2 and 12. In Pascal, if I recall correctly, you get a runtime error as soon as the value is outside the range. I C you just don't have any range checking, just as you don't have any checking of array bounds. – Jabberwocky Apr 09 '14 at 18:42
  • so the best way to convert this to C is use int and add that the input has to be checked for range? (this is not part of a program, but a more of a theoretical question in a homework assignment) – littlerunaway Apr 09 '14 at 18:45

1 Answers1

1

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; 
merlin2011
  • 71,677
  • 44
  • 195
  • 329