【发布时间】:2017-03-29 18:25:06
【问题描述】:
当我尝试将枚举变量初始化为全局变量时,即在任何范围之外,我无法理解这种情况。例如,如果我尝试编译以下代码:
#include <stdio.h>
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;
card = club;
int main()
{
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}
发生以下编译错误:
prog.c:9:1: warning: data definition has no type or storage class
card = club;
^
prog.c:9:1: warning: type defaults to 'int' in declaration of 'card' [Wimplicit-int]
prog.c:9:1: error: conflicting types for 'card'
prog.c:8:3: note: previous declaration of 'card' was here
} card;
^
但是当我将初始化放在 main() 范围内时,不会出现如下代码所示的错误:
#include <stdio.h>
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3
} card;
int main()
{
card = club;
printf("Size of enum variable = %d bytes", sizeof(card));
return 0;
}
输出是:
Size of enum variable = 4 bytes
【问题讨论】:
-
card = club是一个语句,不能在函数体之外有语句。
标签: c enums scope initialization variable-assignment