1、枚举类型
什么时候会用到枚举类型呢,当一个变量只有限定值可取的时候。枚举,即将变量的值一一列举出来。C语言中,对于枚举元素是按常量处理的,定义时默认值是0 1 2 3.。。。
当然,也可以改变枚举变量的值。
enum color{red, green,blue};
enum color mycolor;
mycolor = red;
enum color{red=5, green,blue} mycolor1;
一般我们如果想利用枚举变量的值,但是又不想用0 1 2 3来表示,则我们可以其它名字来表示。
2、typedef类型定义
通过typedef声明新的类型名来代替已有的类型名字;用的较多便是结构体类型的定义
比如:
typedef int myINT;
typedef double muDOUBLE;
typedef struct {
int num;
int age;
}student;
#include <stdlib.h>
#include <stdio.h>
//定义枚举
enum weekDay{
MON, //0
TUES, //1
WED, //2
THUR, //3
FRI
};
//type定义类型
typedef struct{
int num;
int age;
char sex;
}Person;
//声明一个整形数组类型
typedef int NUM10[10];
int main(){
enum color{ red, green, blue };
enum color mycolor;
mycolor = red;
//定义一个枚举变量,并赋值
enum weekDay myday;
//myday = 1;//ERROR
myday = TUES;
printf("Data:%d\n", myday);
//枚举变量的使用
enum weekDay day1;
int dayNum;
printf("input a num:");
scanf("%d", &dayNum);
day1 = (enum weekDay)dayNum;//类型转换为枚举类型
switch (day1){
case MON:
printf("monday\n");
break;
case TUES:
printf("tuesday\n");
break;
case WED:
printf("wedsday\n");
break;
case THUR:
printf("thursday\n");
break;
}
//test struct
Person one;
one.age = 12;
one.num = 10010;
one.sex = 'F';
printf("Person: %d %d %c\n", one.age, one.num, one.sex);
NUM10 array;
for (int i = 0; i < 10; i++){
array[i] = i + 1;
}
for (int i = 0; i < 10; i++){
printf("%5d", array[i]);
}
puts("\n");
}
结果: