1.1枚举类型的使用方法
enum是C语言中的一种自定义类型
enum值是可以根据需要自定义的整型值
第一个定义的enum的值默认为0
默认情况下的enum值是在前一个定义值的基础上加1
enum类型的变量只能取定义时的离散值
1.2枚举类型的特殊意义
enum中定义的值是C语言中真正意义上的常量
在工程中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;
}
实验结果
2.1 sizeof关键字的用法
sizeof是编译器的内置指示符
sizeof用于计算类型或变量所占的内存大小
sizeof的值在编译器就已经确定
2.2 为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;
}
实验结果
3.1 typedef的意义
typedef用于给一个已经存在的数据类型重命名
typedef本质上不能产生新的类型
typedef重命名的类型
-可以在typedef语句之后定义
-不能被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;
Point p; // struct _tag_point
SoftArray* sa = NULL;
ListNode* node = NULL; // struct _tag_list_node*
return 0;
}
用法:
typedef type new_name;
相关实验代码
#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;
}
说明:
喝水不忘挖井人,相关内容均转自狄泰软件学院,唐老师相关讲述