<C> enumeration union

1. Enumeration

1. An enumeration is a constant array of a type

2. Keyword: enum

1  enum Week {MON, TUE, WED, THU, FRI, SAT, SUN};

3. Declare an enum Week w then the size of sizeof(w) is 4

w can be equal to any of the above seven can only be assigned within the scope

By default, no assignment is made. The first one starts from 0. MON=0 TUE=1 and so on

But for example assigning THU to make THU=100 then FRI is 101

The reason the size is 4 is because it is a variable of type int

4. Function: easy to read the code

Enumerations can be replaced by macros. It can also be said that enumerations are also a way to declare constants.

1 #include<stdio.h>
 2  
3  enum Week {MON,TUE,WED,THU,FRI,SAT,SUN};
 4  enum CaiQuan {JIANDAO,SHITOU = 100 ,BU};
 5  
6  int main()
 7  {
 8      enum CaiQuan cq = BU;
 9  
10      switch (cq)
 11      {
 12      case JIANDAO:
 13          printf( " %d\n " ,JIANDAO);
 14          break ;
 15      case SHITOU:
 16          printf( "%d\n",SHITOU);
17         break;
18     case BU:
19         printf("%d\n",BU);
20         break;
21     }
22 
23     return 0;
24 }

2. Consortium

All members of the union share a piece of memory The size of the union depends on the size of the largest member

 1 #include<stdio.h>
 2 
 3 typedef union MyUnion
 4 {
 5     int a;
 6     short b;
 7     char c;
 8     int d;
 9 }MU;
10 
11 int main()
12 {
13     MU mu;
14     int n;
15 
16     n = sizeof(mu);
17 
18     /*mu.a = 10;
19     printf("%d\n",mu.b);
20 
21     mu.c = 100;
22     printf("%d\n",mu.a);*/
23 
24     mu.c = 1;
25     printf("%d\n",mu.a);
26 
27     return 0;
28 }

Description: This code is garbled when outputting

Because c is char with only one byte but a is of int type with four bytes

But if the following two lines are commented out and the four lines commented out above are released, it can be output normally because a has already been assigned a value

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325163100&siteId=291194637