The concept, characteristics, and calculation of a coalition

Table of contents

Union customization

Features of the union

Calculation of the Union


Union customization

A union is a special custom type. The variables defined by this type also contain a series of members. The characteristic is that these members share the same space (so the union is also called a union). For example, the following code

//联合类型的声明
union Un
{
    char c;
    int i;
};

//联合变量的定义
union Un un;
//计算这个变量的大小
printf("%d\n",sizeof(un));

The addresses of the members in the union are the same, but may occupy different byte sizes.

A consortium can only use one member at a time.

Features of the union

The members of a union share the same memory space, so the size of a union variable is at least the size of the largest member, so that the union can at least save the largest member.

Determine the big and small endian storage of the current computer

int main()
{
    int a = 1;
    if(*(char *)&a == 1)
        printf("小端");
    else
        printf("大端");
    return 0;
}

//利用联合体进行判断大小端,因为是要利用int类型的第一个字节进行判断
int panduan()
{
	union Un
	{
		char c;
		int a;
	}u;
	u.a = 1;
	//if (u.c == 1)
	//{
	//	return 1;
	//}
	//else
	//{
	//	return 0;
	//}
    reuturn u.c;
}


int main()
{
	int ret;
	ret = panduan();
	if (ret == 1)
	{
		printf("小端");
	}
	else
	{
		printf("大端");
	}
	return 0;
}

Calculation of the Union

Different from structures, unions generally occupy the largest byte of memory among the members, which is the size of the union, but the size of the union is also an integer multiple of the maximum alignment number among the members.

Guess you like

Origin blog.csdn.net/2301_77868664/article/details/130674455