c union in struct

Solutions on MaxInterview for c union in struct by the best coders in the world

showing results for - "c union in struct"
Isabel
16 Oct 2019
1/* A union within a structure allows to use less memory to store different
2 * types of variables
3 * It allows to store only one variable described in the union instead of
4 * storing every variable type you need
5
6 * For example, this structure stores either an integer or a float and 
7 * has a field which indicates what type of number is stored
8*/
9#include <stdio.h>
10
11struct number
12{
13    char *numberType;
14    union
15    {
16        int intValue;
17        float floatValue;
18    };
19};
20
21static void print_number(struct number n)
22{
23    if (n.numberType == "integer")
24        printf("The number is an integer and its value is %d\n", n.intValue);
25    else if (n.numberType == "float")
26        printf("The number is a float and its value is %f\n", n.floatValue);
27}
28
29int main() {
30   
31   struct number a = { 0 };
32   struct number b = { 0 };
33
34   a.numberType = "integer";  // this structure contains an integer
35   a.intValue = 10;
36
37   b.numberType = "float";  // this structure contains a float
38   b.floatValue = 10.56;
39
40   print_number(a);
41   print_number(b);
42
43   return 0;
44}
45
46/* A union is used just like a structure, the operators . and -> 
47 * give access to the fields
48*/