如果C程序将bitwise-not运算符(〜)应用于布尔值,那么是否调用Undefined Behavior?
例如.以下程序是否定义明确?
bool f = false; bool f2 = ~f; // is f2 guaranteed to be true,or is this UB? bool t = true; bool t2 = ~t; // is t2 guaranteed to be false,or is this UB?
(是的,我知道有一个更适合这种事情的运算符,为了这个问题的目的,我们将忽略它的存在))
解决方法
5.3.1/10 The operand of
~
shall have integral or unscoped enumeration type; the result is the one’s complement of its operand. Integral promotions are performed. [emphasis mine]4.5/6 A prvalue of type
bool
can be converted to a prvalue of typeint
,withfalse
becoming zero andtrue
becoming one.4.5/7 These conversions are called integral promotions.
所以〜false是一个int模式,其中包含所有的位模式 – 一个代表0的位模式的补码,即所有零(3.9.1 / 7所要求的).同样,〜true是一个int的补码1的位表示,即具有最低有效位零的所有位.这两个值都将在布尔上下文中求值.