问题1:enum、sizeof、typedef的意义与用法?
问题2:typedef能产生新的数据类型吗?
枚举类型的使用方法
1、enum是C语言中的一种自定义类型;
2、enum值是可以根据需要自定义的整型值;
3、第一个定义的enum值默认为0;
4、默认情况下的enum值是在前一个定义值的基础上加1;
5、enum类型的变量只能取定义时的离散值;
enum Color
{
GREEN,
RED = 2,
BLUE
};
enum Color c = GREEN;
printf("%d\n",c);
枚举类型的特殊意义
1、enum中定义的值是C语言中真正意义上的常量;
2、在工程中enum多用于定义整形常量;
enum // 无名枚举,用于定义常量
{
ARRAY_SIZE = 10; //定义数组大小
};
int array[ARRAY_SIZE] = {0};
int i = 0;
for(i=0; i<ARRAY_SIZE; i++)
{
array[i] = i + 1;
}
例子:enum的使用
#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;
}
sizeof关键字的用法
1、sizeof是编译器的内置指示符;
2、sizeof用于计算类型或变量所占的内存大小;
3、sizeof的值在编译器就已经确定;
sizeof用于类型: sizeof(type)
sizeof用于变量: sizeof(var) 或 sizeof var
int var = 0;
printf(“%d\n”,sizeof(int));
printf(“%d\n”,sizeof(var));
printf(“%d\n”,sizeof(int));
为sizeof关键字正名
sizeof是C语言的内置关键字,不是函数
在编译过程中所有的sizeof将被具体的数值所替换
程序的执行过程与sizeof没有任何关系
下面的程序输出什么?
int var = 0;
int size = sizeof(var++);
printf("var = %d,size = %d\n",var,size);
例子: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;
}
typedef的意义
1、typedef用于给一个已经存在的数据类型重命名;
2、typedef本质上不能产生新的类型;
3、typedef重命名的类型:
可以在typedef语句之后定义
不能被unsigned和signed修饰
typedef type new_name;
例子:用法:typedef使用示例
#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;
Point p; // struct _tag_point
SoftArray* sa = NULL;
ListNode* node = NULL; // struct _tag_list_node*
return 0;
}
总结:
1、enum用于定义离散值类型;
2、enum定义的值是真正意义上的常量;
3、sizeof是编译器的内置指示符;
4、sizeof不参与程序的执行过程;
5、typedef用于给类型重命名:重名的类型可以在typedef语句之后定义。