Search code examples
clogicunions

How to know which variable value is set for 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
 };

Solution

  • 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
    }
    

    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.