Skip to content

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📌

结构类型📌

声明结构类型📌

1
2
3
4
5
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;
}

声明结构的形式📌

📌
1
2
3
4
5
6
7
struct point{
    int x;
    int y;
};

struct point p1,p2;
//p1和p2都是pointer,里面有x和y的值
📌
1
2
3
4
5
struct{
    int x;
    int y;
}p1,p2;
//p1和p2都是一种无名结构,里面有x和y
📌
1
2
3
4
5
struct point{
    int x;
    int y;
}p1,p2;
//p1和p2都是pointer,里面有x和y的值t

Note

对于第一和第三种形式,都声明结构point。但是第二种形式没有声明point,只是定义了两个变量

结构的初始化📌

1
2
3
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)

1
2
3
4
struct date *p =&myday;

(*p).month=12;//①
p->month=12;//②

->表示指针所指的结构变量中的成员