Understanding Unions in C Language: A Single Entity with Multiple Identities!

In the C language, a union is a special custom data type that allows different types of data to be stored in the same memory location. Unlike a structure, all members of a union share the same memory segment, which means that at any given time, a union can only store the value of one member.

Understanding Unions in C Language: A Single Entity with Multiple Identities!

Definition of Union

The definition format of a union is as follows:

union union_name { member_list};

For example, to define a union that contains an integer, a character, and a double:

union data {    int n;    char ch;    double f;};

You can create variables while defining the union:

union data {    int n;    char ch;    double f;} a, b, c;

Or omit the union name:

union {    int n;    char ch;    double f;} a, b, c;

Memory Distribution of Union

All members of a union share the same memory, and the memory size is equal to the size of the largest member. For example:

union data { int n; char ch; short m;};

In this example, a variable of type data occupies memory equal to the size of the largest member, which is 4 bytes. The following code demonstrates the memory distribution of the union and the mutual influence between members:

#include <stdio.h>union data {    int n;    char ch;    short m;};int main() {    union data a;    printf("%d, %d\n", sizeof(a), sizeof(union data));    a.n = 0x40;    printf("%X, %c, %hX\n", a.n, a.ch, a.m);    a.ch = '9';    printf("%X, %c, %hX\n", a.n, a.ch, a.m);    a.m = 0x2059;    printf("%X, %c, %hX\n", a.n, a.ch, a.m);    a.n = 0x3E25AD54;    printf("%X, %c, %hX\n", a.n, a.ch, a.m);    return 0;}

Output:

4, 440, @, 4039, 9, 392059, Y, 20593E25AD54, T, AD54

Understanding Unions in C Language: A Single Entity with Multiple Identities!

From the results, it can be seen that the members of the union influence each other; modifying the value of one member affects the others.

Application Scenarios of Union

Unions are less commonly used in general programming but are more prevalent in embedded systems and microcontroller programming. A common application scenario is handling different types of data. For example, consider a table containing student and teacher information. Student information includes name, ID, gender, profession, and score, while teacher information includes name, ID, gender, profession, and teaching subject. A union can be used to store this information:

#include <stdio.h>#include <stdlib.h>#define TOTAL 4  // Total number of peoplestruct {    char name[20];    int num;    char sex;    char profession;    union {        float score;        char course[20];    } sc;} bodys[TOTAL];int main() {    int i;    // Input personnel information    for(i=0; i<TOTAL; i++) {        printf("Input info: ");        scanf("%s %d %c %c", bodys[i].name, &(bodys[i].num), &(bodys[i].sex), &(bodys[i].profession));        if(bodys[i].profession == 's') {  // If student            scanf("%f", &bodys[i].sc.score);        } else {  // If teacher            scanf("%s", bodys[i].sc.course);        }        fflush(stdin);    }    // Output personnel informationprintf("\nName\t\tNum\tSex\tProfession\tScore / Course\n");    for(i=0; i<TOTAL; i++) {        if(bodys[i].profession == 's') {  // If studentprintf("%s\t%d\t%c\t%c\t\t%f\n", bodys[i].name, bodys[i].num, bodys[i].sex, bodys[i].profession, bodys[i].sc.score);        } else {  // If teacherprintf("%s\t%d\t%c\t%c\t\t%s\n", bodys[i].name, bodys[i].num, bodys[i].sex, bodys[i].profession, bodys[i].sc.course);        }    }    return 0;}

Output:

Input info: HanXiaoXiao 501 f s 89.5↙Input info: YanWeiMin 1011 m t math↙Input info: LiuZhenTao 109 f t English↙Input info: ZhaoFeiYan 982 m s 95.0↙

Name Num Sex Profession Score / CourseHanXiaoXiao 501 f s 89.500000YanWeiMin 1011 m t mathLiuZhenTao 109 f t EnglishZhaoFeiYan 982 m s 95.000000

Understanding Unions in C Language: A Single Entity with Multiple Identities!

This example demonstrates how convenient unions are for handling different types of data.

Conclusion

A union in C language is an important data type. Although it is less commonly used in general programming, it plays a significant role in embedded systems and microcontroller programming. By using unions, memory space can be effectively saved, and different types of data can be flexibly handled. I hope this article helps you better understand and utilize unions in C language.

Leave a Comment