📜  c union in struct - C 编程语言代码示例

📅  最后修改于: 2022-03-11 15:04:34.006000             🧑  作者: Mango

代码示例1
/* A union within a structure allows to use less memory to store different
 * types of variables
 * It allows to store only one variable described in the union instead of
 * storing every variable type you need

 * For example, this structure stores either an integer or a float and 
 * has a field which indicates what type of number is stored
*/
#include 

struct number
{
    char *numberType;
    union
    {
        int intValue;
        float floatValue;
    };
};

static void print_number(struct number n)
{
    if (n.numberType == "integer")
        printf("The number is an integer and its value is %d\n", n.intValue);
    else if (n.numberType == "float")
        printf("The number is a float and its value is %f\n", n.floatValue);
}

int main() {
   
   struct number a = { 0 };
   struct number b = { 0 };

   a.numberType = "integer";  // this structure contains an integer
   a.intValue = 10;

   b.numberType = "float";  // this structure contains a float
   b.floatValue = 10.56;

   print_number(a);
   print_number(b);

   return 0;
}

/* A union is used just like a structure, the operators . and -> 
 * give access to the fields
*/