我试着在c语言中学习枚举,我怀疑枚举变量在我声明之后是否显示错误,但是当我通过函数使用它时,相同的代码仍然可以正常工作?
显示错误的代码:
变量per1和per2显示错误,原因是什么?
enum mar_status
{
single = 100, married = 200, divorced = 300, widowed = 400
};
enum mar_status per1, per2;
per1 = single;
per2 = married
运行良好的代码:
#include<stdio.h>
void global();
int main(){
global();
return 0;
}
void global(){
enum mar_status
{
single = 100, married = 200, divorced = 300, widowed = 400
};
enum mar_status per1, per2;
per1 = single;
per2 = married;
printf("The person 1 is %d and person 2 is %d\n",per1,per2);
}
感谢帮助我解决问题的人!
最佳答案
C不允许在函数之外使用可执行语句。
前五行是声明,是正确的。
最后两行是可执行语句:
per1 = single;
per2 = married;
必须放在函数中,例如在第二段代码中。
如果要将初始值保留在函数外部,也可以使用初始值进行声明:
enum mar_status {
single = 100, married = 200, divorced = 300, widowed = 400 };
enum mar_status per1 = single;
enum mar_status per2 = married;
int main(){
printf("The person 1 is %d and person 2 is %d\n",per1,per2);
return 0;
}