bool变量如何不等于True和False? [英] How can bool variable be not equal to both True and False?
问题描述
根据该问题的可接受答案
如果…else如果带有else子句的构造终止,有什么好处?
According to accepted answer of this question What is the benefit of terminating if … else if constructs with an else clause?
有一个腐败案(在嵌入式系统中) )可能会导致 bool变量 (1位) 与True和False都不同,这表示
There is a corruption case (in embedded system) that can cause a bool variable (which is 1 bit) differ to both True and False, it means the else
path in this code could be covered instead of be a dead code.
if (g_str.bool_variable == True) {
...
}
else if (g_str.bool_variable == False) {
...
}
else {
//handle error
}
我尝试找出问题所在
有可能吗?
和
如何?
编辑:为了更清楚地说明,我将给出布尔变量,例如:
For more clearly, I will give the declaration of the bool variable like:
struct {
unsigned char bool_variable : 1;
} g_str;
并定义:
#define True 1
#define False 0
推荐答案
unsigned char bool_variable:1
不是布尔变量。它是一个1位整数位字段。 _Bool bool_variable
是布尔变量。
unsigned char bool_variable : 1
is not a boolean variable. It is a 1 bit integer bit-field. _Bool bool_variable
is a boolean variable.
位字段应具有类型是
_Bool
,signed int
,unsigned int $的合格或不合格版本。 c $ c>或其他一些实现定义的类型。是否允许原子类型由实现定义。 > C11dr§6.7.2.1
A bit-field shall have a type that is a qualified or unqualified version of
_Bool
,signed int
,unsigned int
, or some other implementation-defined type. It is implementation-defined whether atomic types are permitted. > C11dr §6.7.2.1
因此立即 unsigned char bool_variable:1
如果这样的实现处理了 unsigned char
位字段(例如 int
位字段),因为 unsigned char
范围可以适合 int
范围,然后出现1位 int
位域的问题。由实现定义的是1位 int
位字段采用的值是 0、1
还是 0,-1
。这会导致此 if()
块的 // handle错误
子句。
If such an implementation treated unsigned char
bit-fields like int
bit-fields, as unsigned char
range can fit in int
range, then troubles occur with 1-bit int
bit-fields. It is implementation defined if a 1-bit int
bit-field takes on the values of 0, 1
or 0, -1
. This leads to the //handle error
clause of this if()
block.
if (g_str.bool_variable == True) { // same as if (g_str.bool_variable == 1)
...
}
else if (g_str.bool_variable == False) { // same as if (g_str.bool_variable == 0)
...
}
else {
//handle error
}
解决方案是简化 if()
测试:
if (g_str.bool_variable) {
...
}
else {
...
}
具有位域,它是C中的一个角,其中 unsigned int
, signed int
是不同的,但是 int
的位域小于 int
的全宽被视为 signed int
或 unsigned int
。对于位域,最好是显式的,并使用 _Bool
, signed int
, unsigned int
。注意:使用 unsigned
与 unsigned int
是同义的。
With bit-fields, it is a corner in C where unsigned int
, signed int
are different, but int
bit-fields less than the full width of an int
may be treated as signed int
or unsigned int
. With bit-fields, it is best to be explicit and use _Bool
, signed int
, unsigned int
. Note: using unsigned
is synonymous with unsigned int
.
这篇关于bool变量如何不等于True和False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!