Answers for "c union in struct"

C
1

c union in struct

/* 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 <stdio.h>

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
*/
Posted by: Guest on September-15-2021

Code answers related to "C"

Browse Popular Code Answers by Language