How to represent enums as parameters in the C language?
In C language, enums can be used as parameters in functions. The specific syntax is as follows:
#include <stdio.h>
// 定义一个枚举类型
enum Weekday {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
// 函数接受一个枚举类型作为参数
void printWeekday(enum Weekday day) {
switch (day) {
case Monday:
printf("星期一\n");
break;
case Tuesday:
printf("星期二\n");
break;
case Wednesday:
printf("星期三\n");
break;
case Thursday:
printf("星期四\n");
break;
case Friday:
printf("星期五\n");
break;
case Saturday:
printf("星期六\n");
break;
case Sunday:
printf("星期日\n");
break;
default:
printf("无效的日期\n");
break;
}
}
int main() {
enum Weekday today = Tuesday;
printWeekday(today);
return 0;
}
In the example above, we defined an enum type Weekday to represent the work days of a week. Then, we defined a function called printWeekday that takes a parameter day of type Weekday and prints out the corresponding day of the week based on the value of day. In the main function, we created a variable today of type Weekday and assigned it the value Tuesday, then passed today as a parameter to the printWeekday function.
The outcome will be:
星期二