1、枚举类型的使用方法
enum是C语言中的一种自定义类型
enum值可以根据需要自定义整形值
第一个定义的enum值默认为0
默认情况下的enum值是在前一个定义值的基础上加1
enum类型的变量只能取定义时的离散值
enum Color
{
GREEN,
RED = 2;
BLUE
};
enum Color c = GREEN;
printf("c = %d\n", c);
2、枚举类型的特殊意义
enum中定义的值是C语言中真正意义上的常量
在工程中enum多用于定义整形常量
enum //无名枚举
{
ARRAY_SIZE = 10; //定义数组大小
}
int array[ARRAY_SIZE] = {0};
int i = 0;
for(i=0;i<ARRAY_SIZE;i++)
{
array[i] = i+1;
}
3、实例分析
enum的使用 11-1.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;
}
扩展 (importance)
#include <iostream>
using namespace std;
class Test
{
public:
enum Color
{
green,
yellow,
red,
blue = 9,
black
};
};
int main()
{
cout << Test::green << endl; //此种方式很常见
cout << Test::black << endl;
return 0;
}
一般人肯定认为应该是Test::Color::green,但实际上枚举里定义的常量作用域属于定义枚举的作用域如这里的Test,
也就是说不能下面这样,会重定义(同一个作用域定义两个同样枚举值)
class Test
{
public:
enum Color
{
green,
yellow
};
enum ColorTwo
{
green //error C2365: “Test::green”: 重定义
};
};
C++11推出了限定作用域的枚举如enum class Color {green};
4、sizeof关键字的用法
sizeof是编译器的内置指示符
sizeof用于计算类型或变量所占内存大小
sizeof的值在编译期就已经确定
- sizeof用于类型:sizeof( type )
- sizeof用于变量:sizeof(var)或 sizeof var
5、为sizeof关键字正名
sizeof是C语言的内置关键字而不是函数
- 在编译过程中所有的sizeof将被具体的数值所替换
- 程序的执行过程与sizeof没有任何关系
下面的程序输出什么?
int var=0;
int size = sizeof( var++ );
printf("var=%d,size=%d\n",var,size);
6、编程实验
sizeof的本质 11-2.c
#include <stdio.h>
int f()
{
printf("QQ:1483306601\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;
}
6、typedef的意义
考官 : 你能说说typedef具体的意义吗?
应聘者 : typedef用于定义一种新的类型。(X)
typedef用于给一个已经存在的数据类型起个别名
typedef本质不能产生新的类型
typedef重命名的类型:
可以在typedef语句之后定义
不能被unsigned和signed修饰
用法:typedef type new_name;
7、实例分析
typedef使用示例 13-1.c
#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;
}
8、小结
enum用于定义离散值类型
enum定义的值是真正意义上的常量
sizeof是编译器的内置指示符
sizeof不参与程序的执行过程
typedef用于给类型起别名
- 别名的类型可以在typedef语句之后定义