即使在C中声明后,枚举变量也显示错误

时间:2018-01-25 12:13:13

标签: c enums

我试着学习c中的枚举,我的疑问是enum变量显示错误,即使在我声明它之后但是当我通过函数使用它时,相同的代码工作正常吗?

显示错误的代码:

变量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);
}    

感谢有助于解决我的问题的人!

1 个答案:

答案 0 :(得分:1)

C不允许在函数外部使用可执行语句。 前五行是声明并且是正确的。 最后两行是可执行语句:

per1 = single;
per2 = married;

并且必须放在一个函数中,例如main与第二段代码一样。

如果您想将声明保留在函数之外,也可以使用初始值进行声明:

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;
}