Regarding the questions left at the end of the previous article on structures in C language, I have completed the explanation and published it on Bilibili. If you are interested, you can take a look. Here is the link:https://www.bilibili.com/video/BV1tSYDzoEmd?vd_source=abed82db08f64a03325f5e43fb10c5ec
What exactly is a union?
A union, also known as a variant record, is a special data type that allows you to store different data types in the same memory space.
Core Features:
-
All members share the same memory. Changing the value of one member can likely affect the values of other members because they use the same “box”.
-
The size of the box is determined by the largest member.
- At any time, only one item can be inside; if a new one is added, the old one is pushed out.
Imagine you have a toolbox, but this toolbox is special; it has several slots for tools (like a screwdriver slot, hammer slot, etc.), but at any one time, you can only use one tool. If you put the hammer in, the screwdriver must come out, or it will be crushed by the hammer.This “special toolbox” is the union in C language.
Why do we need it? What are its use cases?
Imagine a scenario:
When writing a program, a certain variable sometimes stores an integer, sometimes a float, and sometimes a string. You don’t want to waste three blocks of memory at the same time; you just want to use “one sufficiently large memory” and switch as needed—this is the value of a union.
How to declare a union?
Defining a union is very similar to defining a structure; you just replace the keyword struct with union. The format is as follows:
union UnionName { MemberType MemberName1; MemberType MemberName2; // ... can have more members};
Example
union DataInfo { int i; // Integer member double f; // Floating-point member char str[30]; // Character array member (string)};
Now, union DataInfo is a new data type, and there are other definition forms, such as using the typedef keyword, which is similar to structures. You can refer to the previous article on structures in C language.How to use it?Like a structure, first declare a variable, then use the . operator to access its members.One thing to note is that members share memory, so when you assign a value to one member and then read another member, the value may be meaningless (it is another interpretation of the previous data in memory, which may be garbage value).Example program
#include <stdio.h>#include <string.h>// 1. First define our unionunion DataInfo { int i; float f; char str[30];};int main() { // 2. Declare a union variable data union DataInfo data; // 3. Use the union's members // Now I want to store an integer data.i = 10; printf( "data.i : %d\n", data.i); // Output: data.i : 10 // Now I want to store a float, which will overwrite the previous integer data.f = 220.5; printf( "data.f : %.2f\n", data.f); // Output: data.f : 220.50 // Note! At this point, reading data.i will not yield 10 anymore, but a bunch of garbled characters (because the memory has been overwritten by the binary data of the float 220.5) printf( "data.i is now meaningless: %d\n", data.i); // Outputs a strange number // Now I want to store a string strcpy( data.str, "PLC"); printf( "data.str : %s\n", data.str); // Output: data.str : PLC // Similarly, now the values of data.i and data.f also become meaningless; the size of the union is the size of the largest member printf("The size of the union is: %zu",sizeof(data)); return 0;}
The compilation and running results are as follows:
Regarding the final display of the union size being 32 instead of 30, you can refer to the memory principle video at the beginning of the article on Bilibili.Well, that concludes our basic concept of unions today. Practice more and understand better; I believe this will not be a problem for everyone. In the next lesson, we will discuss the bit-field concept in C language. See you next class (づ。◕‿‿◕。)づ