第11课 enum,sizeof,typedef分析

枚举类型的使用方法:

enum的地位和struct是相等的,enum主要用来根据需要定义一些离散的值。

枚举类型的特殊意义:

工程中常用无名枚举来定义常量。

程序示例:

 1 #include <stdio.h>
 2 
 3 enum
 4 {
 5     ARRAY_SIZE = 10
 6 };
 7 
 8 enum Color
 9 {
10     RED    = 0x00FF0000,
11     GREEN  = 0x0000FF00,
12     BLUE   = 0x000000FF
13 };
14 
15 void PrintColor(enum Color c)
16 {
17     switch( c )
18     {
19         case RED:
20             printf("Color: RED (0x%08X)
", c);
21             break;
22         case GREEN:
23             printf("Color: GREEN (0x%08X)
", c);
24             break;
25         case BLUE:
26             printf("Color: BLUE(0x%08X)
", c);
27             break;
28     }
29 }
30 
31 void InitArray(int array[])
32 {
33     int i = 0;
34     
35     for(i=0; i<ARRAY_SIZE; i++)
36     {
37         array[i] = i + 1;
38     }
39 }
40 
41 void PrintArray(int array[])
42 {
43     int i = 0;
44     
45     for(i=0; i<ARRAY_SIZE; i++)
46     {
47         printf("%d
", array[i]);
48     }
49 }
50 
51 
52 int main()
53 {
54     enum Color c = GREEN;
55     
56     int array[ARRAY_SIZE] = {0};
57     
58     PrintColor(c);
59     
60     InitArray(array);
61     
62     PrintArray(array);
63     
64     return 0;
65 }

运行结果如下:

sizeof关键字的用法:

sizeof不是函数,而是一个编译器指示符。

示例程序如下:

运行结果如下:

可以看到var的值是0,第7行的var++并没有起作用。因为sizeof在运行期间就确定了类型的大小,var++在编译期间执行,到运行期间就不存在这个操作了。运行期间只存在int var = 0这一个操作了。

 修改程序如下:

再次运行结果如下:

可以看到f函数并没有得到执行。在编译到18行时,编译器发现f的返回值为int,这时候就可以计算出大小了,运行时f函数并没有被调用。

typedef的意义:

typedef不是用来定义新的类型,而是给一个存在的类型重命名。

typedef要重命名的类型可以在typedef语句之后再定义。

重命名的类型不能被unsigned和signed修饰。

程序示例:

 1 #include <stdio.h>
 2 
 3 typedef int Int32;
 4 
 5 struct _tag_point
 6 {
 7     int x;
 8     int y;
 9 };
10 
11 typedef struct _tag_point Point;
12 
13 typedef struct
14 {
15     int length;
16     int array[];
17 } SoftArray; 
18 
19 typedef struct _tag_list_node ListNode;
20 struct _tag_list_node
21 {
22     ListNode* next;
23 };
24 
25 int main()
26 {
27     Int32 i = -100;        // int 
28     //unsigned Int32 ii = 0;
29     Point p;               // struct _tag_point
30     SoftArray* sa = NULL;   
31     ListNode* node = NULL; // struct _tag_list_node*
32     
33     return 0;
34 }

  第19行就是先给类型重命名,然后又定义的类型。编译器在遇到使用ListNode的地方,只需要把它替换成struct _tag_list_node就好了,所以这一行typedef在struct _tag_list_node之前定义没有问题。编译器并不要求被重命名的类型要先定义。

小结:

原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9535043.html