简体   繁体   English

C中的并集和范围变量

[英]unions and ranged variables in C

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). 应该由bool变量的值(在这种情况下为inRoom)决定哪一个。 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? 这是否意味着我不能在struct的声明中输入此内容,而是在程序本身中输入? 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 第二个问题:在pascal中,我可以定义一个仅包含数字范围的变量

Dice=2..12;

how do I convert this to C language? 如何将其转换为C语言? 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? 有没有更好的方法来在C中定义范围变量?

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; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM