C language custom types: unions and enumerations

?Record

1.
Union type declaration

2.
Characteristics of the consortium

3.
Calculation of union

4.
Declaration of enumeration type

5.
Advantages of enumeration types

6.
What are the uses of enumeration types?

1.
consortium

1.1
Union type declaration

Like a structure, a union is also composed of two or more members, and these members can be of different types.

But the compiler only allocates enough memory space for the smallest member. The characteristic of the union is that all members share a block of memory space. Therefore, the consortium is also called:
community
.

Assign a value to one member of the union, and the values of other members will also change.

Let’s look at a code:

#include<stdio.h>
//Union type declaration
union U
{
char C;
int i;
};
int main()
{
//Definition of joint variables
union U u = { 0 };
//Calculate the size of two variables
printf("%d\\
", sizeof(u));
return 0;
}

Why is the result 4?

Let’s look at the characteristics of the consortium

1.2
Characteristics of the consortium

The members of a union share a block of memory space, so the value of a union variable is at least the value of the last member (because the size of the union is small enough to save the last member).

The largest member of the above code is int, which occupies four bytes, so the output result of the previous code is 4.

Let’s continue to analyze this code

#include<stdio.h>
//Union type declaration
union U
{
char C;
int i;
};
int main()
{
//Definition of joint variables
union U u = { 0 };
//Calculate the size of two variables
printf("%d\\
", sizeof(u));
printf("%p\\
", & amp;u);
printf("%p\\
", & amp;(u.i));
printf("%p\\
", & amp;(u.C));
return 0;
}

We see that the address of union u is the same as the address of C’s address i. share the same space.

Look at the second code

#include<stdio.h>
//Union type declaration
union Un
{
    char c;
    int i;
};

int main()
{
    //Definition of joint variables
    union Un un = { 0 };
    un.i = 0x11223344;
    un.c = 0x55;
    printf("%x\\
", un.i);
    return 0;
}

The three addresses output by code 1 are similar. In the output of code 2, we find that the content of the 4th byte of i has been modified to 55.

After careful analysis, we can draw the memory layout diagram of un.

1.3
Pairs of structure and union with the same members?

Let’s compare the memory layout of structures and unions with the same members.

#include <stdio.h>
struct S
{
char c;
int i;

};
int main()
{
struct S s = { 0 };
printf("%d\\
",sizeof(struct S));
return 0;
}

Let’s look at the coalition again

#include <stdio.h>
union Un
{
char c;
int i;
};
int main()
{
union Un un = { 0 };
printf("%d\\
", sizeof(union Un));
}

The storage of the structure in memory can be viewed

C language custom type: structure-CSDN Blog

1.4
Calculation of union

?
The joint members are at least the smallest members

.

?
When the last member value is not an integer multiple of the last pair number, it must be aligned to an integer multiple of the last pair number.

Let’s look at a code

#include<stdio.h>
union Un1
{
    char c[5];//5 1 8 1
    int i;//4 4 8 4
};

union Un2
{
    short c[7];//14 2 8 2
    int i;//4 4 8 4
};

int main()
{
    //What is the result output below?
    printf("%d\\
", sizeof(union Un1));//8
    printf("%d\\
", sizeof(union Un2));//16
    return 0;
}

union Un1
{
char c[5];//5 1 8 1
int i;//4 4 8 4
};
The largest member in Un1 is c, which occupies five bytes, but it is not a multiple of the maximum alignment number of 4, so it must be aligned to 8.

union Un2
{
short c[7];//14 2 8 2
int i;//4 4 8 4
};

The largest member in Un2 is c, which occupies 14 bytes, but it is not the maximum alignment number of 4 bytes, so it needs to be adjusted to 16.

Therefore, the size of the union is the size of the largest member (this sentence is wrong).

Using a union can save space, for example:

For example, if we want to hold an event, we need to launch a gift exchange order. There are three kinds of products in the gift exchange order: books, cups, and shirts.

Each product has: inventory, price, product type and other information related to the product type.

Book: title, author, number

Cup?: Design

Shirt: design, color options, size options

Then we can’t bear to think and write the following structure directly:

#include <stdio.h>
struct gift_list
{
//Public properties
int stock_number;//inventory quantity
double price; // pricing
int item_type;//item type
\t
//Special type
char title[20]; // book title
char author[20];//Author
int num_pages;//Number of pages

char design[30];//Design
int colors;//Color
int sizes;//size
};

The above structure is actually designed to be very simple and easy to implement, but the design of the structure contains various attributes of all gifts, which makes the structure’s layout biased and wastes memory. Because for the products in the gift redemption order, only some attribute information is common. ?like:

If the product is a book, there is no need for design, colors, or sizes.

Therefore, we can write the public attributes separately, and combine the remaining attributes belonging to various commodity entities into a union, so that the required memory space can be introduced and memory can be saved to a certain extent.

struct gift_list
{
int stock_number;//inventory quantity
double price; //pricing
int item_type;//item type

union {
struct
{
char title[20];//book title
char author[20];//Author
int num_pages;//Number of pages
}book;
struct
{
char design[30];//Design
}mug;
struct
{
char design[30];//Design
int colors;//Color
int sizes;//size
}shirt;
}item;
};

1.5
A combined exercise

Write a program to determine whether the current machine is a terminal? Or? End?

Let’s first write a judgment program in the usual way

#include <stdio.h>
int main()
{
int a = 1;
if (*(char*) &a == 1)
{
printf("little endian\\
");
\t\t
}
else
{
printf("Big endian\\
");
}
return 0;
}

vs is little endian

#include <stdio.h>
int main()
{
union
{
char c;
int i;
}u;
u.i = 1;
if (u.c == 1)
printf("little endian\\
");
else
printf("Big endian\\
");
return 0;
}

We can also write it as a function

#include <stdio.h>
int check_sys()
{
union
{
char c;
int i;
}u;
u.i = 1;
return u.c;
}
int main()
{
if (u.c == 1)
printf("little endian\\
");
else
printf("Big endian\\
");
return 0;
}

2.
enumeration type

2.1
Declaration of enumeration type

Enumeration, as the name suggests, is an enumeration.

List the possible values.

Enumerations are represented by enum

?As in our real life:

There are a limited number of 7 days from Monday to Sunday in the week, which can be listed

Gender: male,?, confidential, can also be listed

There are 12 characters in the file, and you can also list them.

Miyuan?, can also be enumerated in meanings

The tables of these data can be enumerated.

#include <stdio.h>
enum Day
{
Mon,//0
Tues,//1
Wed,//2
Thur,//3
Fri,//4
Sat,//5
Sun//6
};
enum Sex//gender
{
MALE,//0
FEMALE,//1
SECRET//2
};
int main()
{
printf("%d %d %d %d %d %d %d\\
", Mon, Tues, Wed, Thur, Fri, Sat, Sun);
printf("%d %d %d\\
", MALE, FEMALE, SECRET);
return 0;
}

defined above
enum Day
,
enum Sex

All are enumeration types.

The contents in {} are possible values of the enumeration type, also called enumeration constants.

These possible values are all valuable, starting from 0 by default and increasing by 1 in sequence. Of course, an initial value can also be assigned when declaring the enumeration type.

enum Day
{
    //Listed are the possible values of the enumeration type
    //These listed possible values are called: enumeration constants
    Mon,//0
    Tues,//1
    Wed,//2
    Thur,//3
    Fri,
    Sat,
    Sun
};

enum Sex
{
    MALE=4,//0
    FEMALE=7,//1
    SECRET=1//2
};

int main()
{
    //printf("%d %d %d %d %d %d %d\\
", Mon,Tues,Wed,Thur,Fri,Sat,Sun);
    printf("%d %d %d\\
", MALE, FEMALE, SECRET);
    //MALE = 4;//ERR
    enum Sex s = MALE;
    enum Day d = Sun;

    return 0;

2.2
Advantages of enumeration types

Why use ? enum?

Can we use it?
#define
To define constants, why use enumerations?

Advantages of enumerations:

1.
Increase code readability and maintainability

2.
Identifiers defined with #define have type checking and are more rigorous than enumerations.

3.
To facilitate debugging, the preprocessing stage will be deleted.
#define
defined symbols

4.
Easy to use, multiple constants can be defined at one time

5.
Enumeration constants follow the scope rules. The enumeration is declared within a function and can only be used within the function.

#include <stdio.h>
void menu()
{
printf("**********************\\
");
printf("*** 1.add 2.sub ***\\
");
printf("*** 3.mul 4.div ***\\
");
printf("*** 0.exit ***\\
");
printf("************************\\
");
}

enum Option
{
EXIT,
ADD,
SUB,
MUL,
DIV
};

//#define EXIT 0
//#define ADD 1
//#define SUB 2
//
//#define XOR 5

int main()
{
int input = 0;
do
{
menu();
printf("Please select:");
scanf("%d", & amp;input);
switch(input)
{
case ADD:

break;
case MUL:

break;
default:
break;
}
} while (input);

return 0;
}

2.3
What are the uses of enumeration types?

#include <stdio.h>
enum Color//color
{
    RED = 1,
    GREEN = 2,
    BLUE = 4
};

int main()
{

    enum Color clr = GREEN;//Use enumeration constants to assign values to enumeration variables
    enum Color clr2 = 2;
    printf("%d\\
", sizeof(clr));//4
    return 0;
}

Is it possible to assign integers to enumeration variables? It is possible in C language, but it is not possible in C++. What type checking does C++ have?

More stringent.

Okay, that’s the end of our custom types: unions and enumerations, see you next time.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Algorithm skill tree Home page Overview 56976 people are learning the system