Horje
c union in struct Code Example
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
*/




C

Related
C printf to string Code Example C printf to string Code Example
bash convert find to array Code Example bash convert find to array Code Example
link list c Code Example link list c Code Example
ubuntu ocaml install Code Example ubuntu ocaml install Code Example
how to check disk space in linux Code Example how to check disk space in linux Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
11