[C language-advanced] detailed enumeration and union

enumerate

First of all, what is the old rule enumeration

Enumeration, as the name suggests, is to enumerate one by one, enumerating every possibility we can think of.
Let me give you an example: Monday to Sunday of the week can be listed, country names can be listed, gender, gender, month, date can be similar to this common type can be listed one by one
.

enum Day
{
    
    
   Mon,
   Tues,
   Wed,
   Thur,
   Fri,
   Sat,
   Sun
};

The above definition is the enumeration constant (Mon Tues and so on) enum Day, which is the enumeration type.
Here we have to remember that the byte size of the enumeration is four bytes

Why use enum

  1. Increase the readability and maintainability of the code
  2. Compared with the identifier defined by #define, the enumeration has type checking, which is more rigorous.
  3. Prevents name pollution (encapsulation)
  4. Easy to debug
  5. Easy to use, you can define multiple constants at one time

How to use enumeration (how to do it)

Enumeration code

enum Color
{
    
    
 RED=1
 GREEN=2,
 BLUE=4
};
enum Color clr=GREEN;

The point to be emphasized here is that the enumeration can only be defined with the values ​​listed above. For example, if the output of RED is 1, it will be increased once if it is not defined by itself.

enum Color
{
    
    
 RED=1
 GREEN,
 BLUE
};

For example, GREEN will be equal to 2 and BLUE will be equal to 3.

Union (union)

What is union

Definition of union type:
Union is also a special custom type. Variables defined by this type also contain a series of members. The characteristic is that these members share the same space (so union is also called union).

//联合类型的声明 
union Un {
    
        char c;    int i; };
//联合变量的定义 
union Un un; 
//计算连个变量的大小 
printf("%d\n", sizeof(un));

Why use consortium

Features: The members of the union share the same memory space. The size of such a union variable is at least the size of the largest member (because the union must at least be able to save the largest member).

How to use consortium

For example

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
union Un
{
    
    
	int i;
	char c;
};
int main()
{
    
    
	union Un u;
		u.i = 1;

		if (u.i == 0x01)
	{
    
    
		printf("min\n");
	}
	else
	{
    
    
		printf("max\n");
	}
	return 0;
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43762735/article/details/109339142