如何知道为联合设置了哪个变量值? [英] How to know which variable value is set for union?

查看:57
本文介绍了如何知道为联合设置了哪个变量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在致力于项目的优化.它包含选项的结构,用户可以在其中一次选择一个选项.除了选项之外,我们还使用标志变量来检查为该记录设置的选项值.为了提高内存效率,我想将struct转换为union.但是我怎么知道哪个变量值是在联合中设置的.因为对并集没有限制,即使没有设置也可以获取变量的值.

I am working on optimization of a project. It contains a struct of an options in which user can select a single option at a time. In addition to the option, we also use a flag variable to check which option value is set for this record. In order to make it memory efficient I want to convert struct into a union. But How do I know that which variable value is set in union. Because there is no restriction in union to fetch a value of a variable even which is not set.

 struct options{
     int basicPay;
     int lumsumPay;
     int mothlyPay;
     int weeklyPay;
     int dailyPay;
     int anualPay;

     int payType;   // Flag variable to check which option is selected
 };

union OptimizeOptions{
    int basicPay;
    int lumsumPay;
    int mothlyPay;
    int weeklyPay;
    int dailyPay;
    int anualPay;

    int payType;   // Confuse at here
 };

推荐答案

您是否尝试过在 struct 内部使用 union ?让我们看下面的等效示例:

Have you tried a union inside of a struct? Let’s see the following example equivalent:

union options{
  int basicPay;
  int lumsumPay;
  int mothlyPay;
  int weeklyPay;
  int dailyPay;
  int anualPay;
};

struct record{
  union options op;   // Options union
  int payType;   // Flag variable to check which option is selected
}

联合( options )将为其最大变量保留内存,您可以设置其值,并且结构(记录)将跟踪该联合存储块和 payType 标志值,该值将告诉您的程序获取并集的垂直变量.

The union (options) will reserve memory for its largest variable and you can set its value and your structure (record) will keep track of that union memory block and the payType flag value could be set which will tell your program to fetch the perticular variable of the union.

这篇关于如何知道为联合设置了哪个变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆