c – 在布尔值上使用按位不是运算符(〜)调用未定义的行为?

如果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 type int,with false becoming zero and true becoming one.

4.5/7 These conversions are called integral promotions.

所以〜false是一个int模式,其中包含所有的位模式 – 一个代表0的位模式的补码,即所有零(3.9.1 / 7所要求的).同样,〜true是一个int的补码1的位表示,即具有最低有效位零的所有位.这两个值都将在布尔上下文中求值.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...