【发布时间】:2017-03-02 12:59:36
【问题描述】:
我正在测试 C 中的代码,其中我有意在结构内定义一个整数位字段(variable not_enough),宽度为 1,但分配需要 2 位或 3 位的值。 重要的是要注意我从枚举中获取值。在此之后,我打印值。我希望得到等于 0 的整数的默认值。但我得到的是交替等于 0 或 1 的值。
你能解释一下原因吗?
下面是代码:
#include <stdio.h>
typedef enum {
FIRST = 9,
SECOND = 8,
THIRD = 7,
FOURTH = 6,
FIFTH = 5,
SIXTH = 4,
SEVENTH = 3,
EIGHTH = 2
} directionValues;
struct {
unsigned int enough : 3;
unsigned int not_enough: 1; //intentionally limited to 1 bit
} test_bit;
int main(void) {
test_bit.enough = EIGHTH;
printf("Enough bits for variable. Value is %d\n",test_bit.enough);
test_bit.not_enough = THIRD;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = FOURTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = FIFTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = SIXTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = SEVENTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = EIGHTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
return 0;
}
输出是:
足够的变量位。值为 2
变量位数不足。值为 1
变量位数不足。值为 0
变量位数不足。值为 1
变量位数不足。值为 0
变量位数不足。值为 1
变量位数不足。值为 0
【问题讨论】:
-
“重要的是要注意我从枚举中获取值” - 不,不是!而且您使用 enum-constants,而不是“枚举”类型。当您认为
1不是 UB 时:您会接受哪种行为作为 UB?
标签: c testing struct enums bit-fields