enum、sizeof、typedef分析
1、枚举类型的使用方法
- enum是C语言中的一种自定义类型
- enum值是可以根据需要自定义的整型值
- 第一个定义的enum值默认为0
- 默认情况下的enum值是在前一个定义值的基础上加1
- enum类型的变量只能取定义时的离散值
代码实践:
#include <stdio.h>
enum Color
{
RED,
GREEN = 2,
BLUE
};
int main(void)
{
printf("RED = %d\n",RED);
printf("GREEN = %d\n",GREEN);
printf("BLUE = %d\n",BLUE);
return 0;
}
输出结果为:
2、枚举类型的特殊意义
enum中定义的值是C语言中真正意义上的常量
代码实践:
#include <stdio.h>
enum
{
ARRAY_SIZE = 10
};
enum Color
{
RED = 0x00FF0000,
GREEN = 0x0000FF00,
BLUE = 0x000000FF
};
void PrintColor(enum Color c)
{
switch( c )
{
case RED:
printf("Color: RED (0x%08X)\n", c);
break;
case GREEN:
printf("Color: GREEN (0x%08X)\n", c);
break;
case BLUE:
printf("Color: BLUE(0x%08X)\n", c);
break;
}
}
void InitArray(int array[])
{
int i = 0;
for(i=0; i<ARRAY_SIZE; i++)
{
array[i] = i + 1;
}
}
void PrintArray(int array[])
{
int i = 0;
for(i=0; i<ARRAY_SIZE; i++)
{
printf("%d\n", array[i]);
}
}
int main()
{
enum Color c = GREEN;
int array[ARRAY_SIZE] = {0};
PrintColor(c);
InitArray(array);
PrintArray(array);
return 0;
}
输出结果为:
3、sizeof关键字的用法
4、sizeof关键字的本质
sizeof是C语言内置关键字而不是函数
- 在编译过程中所有的sizeof将被具体的数值所替换
- 程序的执行过程与sizeof没有关系
代码实践:
#include <stdio.h>
int f()
{
printf("Delphi Tang\n");
return 0;
}
int main()
{
int var = 0;
int size = sizeof(var++);
printf("var = %d, size = %d\n", var, size);
size = sizeof(f());
printf("size = %d\n", size);
return 0;
}
输出结果为:
5、typedef的意义
面试题:说说typedef的具体意义
错误回答:typedef用来定义一种新的类型
正确回答:typedef用来给已经存在的数据类型重命名,typedef本质上不能产生新类型
typedef重命名的类型:
(1)可以在typedef语句之后定义
(2)不能被unsigned和signed修饰
代码实践:
#include <stdio.h>
typedef int Int32;
struct _tag_point
{
int x;
int y;
};
typedef struct _tag_point Point;
typedef struct
{
int length;
int array[];
} SoftArray;
typedef struct _tag_list_node ListNode;
struct _tag_list_node
{
ListNode* next;
};
int main()
{
Int32 i = -100; // int
//unsigned Int32 ii = 0; // error
Point p; // struct _tag_point
SoftArray* sa = NULL;
ListNode* node = NULL; // struct _tag_list_node*
return 0;
}