11 11.1.1 枚举 常量符号化 enum colors { red , yellow , green }
枚举是一种用户定义的数据类型,它用关键字 enum
以如下语法来声明:
enum 枚举类型名字 { 名字0 ,……, 名字n };
enum color { red , yellow , green };
void f ( enum color c );
int main ( void ) {
enum color t = red ;
scanf ( "%d" , & t );
f ( t );
return 0 ;
}
void f ( enum color c ) {
printf ( "%d \n " , c );
}
枚举量可以作为值 枚举类型可以跟上enum
作为类型 但是实际上是以整数 来做内部计算和外部输入输出的 套路:自动计数的枚举 enum COLOR { RED , YELLOW , GREEN , NumCOLORS };
这样需要遍历所有的枚举量或者需要建立一个用枚举量做下标的数组的时候就很方便了
枚举量 声明枚举量 时可以指定值
enum COLOR { RED = 1 , YELLOW , GREEN = 5 };
Info
枚举比const int
方便 枚举比宏(macro)好,因为枚举有int
类型 11.1.2 结构类型 声明结构类型 struct date {
int month ;
int day ;
int year ;
}; //常见错误:漏掉末尾的分号
Tip
和本地变量 一样,在函数内部声明的结构类型只能在函数内部使用 所以通常在函数外部声明 结构类型,这样就可以被多个函数所使用了
struct date {
int year ;
int month ;
int day ;
};
int main ( void ) {
struct date today ; //类型是struct date,名称叫today
today . day = 10 ;
today . month = 12 ;
today . year = 2001 ;
printf ( "Today's date is %i-%i-%i. \n " , today . year , today . month , today . day );
return 0 ;
}
声明结构的形式 ① struct point {
int x ;
int y ;
};
struct point p1 , p2 ;
//p1和p2都是pointer,里面有x和y的值
② struct {
int x ;
int y ;
} p1 , p2 ;
//p1和p2都是一种无名结构,里面有x和y
③ struct point {
int x ;
int y ;
} p1 , p2 ;
//p1和p2都是pointer,里面有x和y的值t
Note
对于第一和第三种形式,都声明 了结构point 。但是第二种形式没有声明point,只是定义 了两个变量
结构的初始化 struct date today = { 07 , 31 , 2024 };
struct date today2 = {. month = 7 ,. year = 2024 }
//不赋值默认初始是0
结构成员 数组 vs 结构
数组 用[]
运算符和下标访问其成员 e.g.a[0]=10
结构 用.
运算符和名字访问其成员
e.g.today.day
结构运算 数组无法 做到
p1 = ( struct point ){ 5 , 10 }; //p1.x=5,p1.y=10
p1 = p2 ; //p1.x=p2.x ; p1.y=p2.y
结构指针 和数组不一样,结构变量名字 并不是结构变量的地址 , 必须 使用&
运算符
struct date * pDate =& today ;
11.1.3 结构与函数 int numberOfDays ( struct date d );
整个结构可以作为参数 的值传入函数
这时候是在函数内新建 一个结构变量,并复制 调用者的结构的值
输入结构 没有直接的方式可以一次scanf一个结构
→在这个输入函数中,完全可以创建一个临时的 结构变量,然后把这个结构返回给调用者
结构 指针 作为参数 Quote "If a large structure is to be passed to a function, it is generally more efficient to pass a pointer than to copy the whole structure"
–K&R(p.131)
struct date * p =& myday ;
( * p ). month = 12 ; //①
p -> month = 12 ; //②
用->
表示指针 所指的结构变量中的成员
February 28, 2025 November 20, 2024