enumerate
enum Sex
{
//枚举的可能取值
MALE,
FEMALE,
SECRET,
};
int main()
{
enum Sex s = MALE;
return 0;
}
Advantages of enums (why use enums):
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. To prevent naming pollution (encapsulation)
4. Easy to debug
5. Easy to use, multiple constants can be defined at a time
union - union
Union is also a special custom type. The defined variable of this type also contains a series of members. The characteristic is that these members share the same space (so union is also called union)
It can be seen that they use the same address, so it is called a union
Combined features:
The members of the union share the same memory space. The size of such a joint variable is at least the size of the largest member (because the union must at least be able to save the largest member)
Practice questions:
Use the union to test whether the machine is big-endian or little-endian
int check_sys()
{
union Un
{
char c;
int i;
}u;
u.i = 1;
//返回1,表示大端
//返回0,表示大端
return u.c;
}
int main()
{
int a = 1;
int ret = check_sys();
if (1 == ret)
{
printf("小端\n");
}
else
printf("小端\n");
}
Calculation of joint size
The size of the union is at least the size of the largest member
When the size of the largest member is not an integer multiple of the maximum alignment, it must be aligned to an integer multiple of the maximum alignment
example:
union Un
{
int a;//4 8 4
char arr[5];//5 1 8 1
};
int main()
{
union Un u;
printf("%d\n", sizeof(u));
return 0;
}
The output value is 8 (multiple of 4)