问题描述
我试图更好地理解C99标准,但现在我对将枚举用作结构中的位域以及是否将它们视为int或实现定义的类型感到困惑.在查找C99的最终草案时,我发现6.7.2.1段. 4
I'm trying to better understand the C99 standard but now I'm confused about using enums as bitfields in structs and if they are treated as int or as implementation-defined type. When looking up in the final draft for C99, I found 6.7.2.1 para. 4
和6.7.2.2段. 4
and 6.7.2.2 para. 4
所以我尝试了这个简单的源代码
So I tried with this simple source code
enum e {
E0, E1
};
struct s {
enum e bitfield : 4;
};
我可以使用-std=c99 -Wall -Wextra -pedantic
使用gcc-5.0和clang-3.5进行编译而不会发出警告,但是我使用gcc-4.8会收到以下警告
I can compile this without warnings with gcc-5.0 and clang-3.5 using -std=c99 -Wall -Wextra -pedantic
but I get the following warning with gcc-4.8
warning: type of bit-field 'bitfield' is a GCC extension
在这里开始混乱.作为位域的枚举是否被视为int或实现定义的类型?这是GCC-4.8中的错误,还是他们更改了对标准的解释?与其他C99编译器一起使用是否安全?
Here start the confusion. Are enums as bitfields treated as int or implemenation-defined type? Is this a bug in GCC-4.8 or did they change their interpretation of the standard? And is it safe to use this with other C99-compiler?
推荐答案
是的
您看到的是gcc的实现定义的行为发生了变化.
What you're seeing is a change in the implementation-defined behavior of gcc.
正如您引用的标准部分所述,位字段必须为_Bool
,int
,unsigned int
,或某种实现定义的类型.
As it says in the section of the standard you quoted, a bit field must be of type _Bool
, int
, unsigned int
, or some implementation-defined type.
enum
类型与某些整数类型兼容.通过实验并查看gcc手册,可以发现对于gcc,您的enum e
与unsigned int
兼容.但是该标准不允许位字段与unsigned int
兼容.它实际上必须是unsigned int
类型(兼容类型不一定是同一类型). 除了,它还可以是其他一些实现定义的类型.
A enum
type is compatible with some integer type. Experiment and a look at the gcc manual shows that for gcc, your enum e
is compatible with unsigned int
. But the standard doesn't permit a bit field to be of a type compatible with unsigned int
. It actually has to be of type unsigned int
(compatible types are not necessarily the same type). Except that it can also be of some other implementation-defined type.
根据 gcc 4.8.4手册:
在严格符合模式下,不允许使用其他类型.
No other types are permitted in strictly conforming mode.
根据gcc-5.2.0的手册:
According to the manual for gcc-5.2.0:
即使在严格符合的模式下,也允许使用其他整数类型(例如long int
)和枚举类型.
Other integer types, such as long int
, and enumerated types are permitted even in strictly conforming mode.
因此,您所看到的是gcc的行为发生了变化,即使在严格符合模式"下,也允许更多类型的位字段.这并不是gcc对标准的解释的变化;两种行为都是允许的.
So what you're seeing is a change in the behavior of gcc, allowing more types for bit fields even in "strictly conforming mode". This is not a change in gcc's interpretation of the standard; both behaviors are permitted.
使用enum
作为位字段是不可移植的.合格的C编译器可能支持也可能不支持. (如果gcc保持对此发出警告的能力,我个人会更喜欢.)
Using enum
s as bit fields is not portable. A conforming C compiler may or may not support them. (I personally would have preferred it if gcc had kept the ability to get a warning for this.)
这篇关于枚举是位域实现定义的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!