【发布时间】:2016-01-29 01:53:41
【问题描述】:
根据这个问题的接受答案 What is the benefit of terminating if … else if constructs with an else clause?
有一个损坏情况(在嵌入式系统中)可能导致 bool 变量 (1 位) True 和 False 不同 strong>,这意味着这段代码中的else路径可以被覆盖而不是死代码。
if (g_str.bool_variable == True) {
...
}
else if (g_str.bool_variable == False) {
...
}
else {
//handle error
}
我试图找出答案,但仍然没有任何线索。
有可能吗? 和 如何?
编辑:为了更清楚,我将给出 bool 变量的声明,如:
struct {
unsigned char bool_variable : 1;
} g_str;
同时定义:
#define True 1
#define False 0
【问题讨论】:
-
你需要出示
bool_variable的声明。 -
可能
bool_variable的类型实际上并不是_Bool。顺便说一句,不管它是什么,它至少是 8 位的。除了位域,没有 1 位变量。 -
要获得路径覆盖,通常使用
if (bool_variable)和else。 -
从引用的另一个问题转述:内存损坏或溢出可能导致垃圾值在那里被覆盖。一般来说,除非您需要在代码中进行超级防御(编写操作系统或其他东西来保护核发射代码),否则您不应该担心它。使用模式
if (boolvar) {...} else {...}而不是比较真/假 -
在标准 C 中,位域只能是
_Bool、int或unsigned int。是否允许unsigned char bool_variable : 1;是实现定义的。这意味着您的编译器应该记录此代码的行为并解释允许的值是什么。