加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:54:06 所属栏目:百科 来源:网络整理
导读:如果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,
如果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的位表示,即具有最低有效位零的所有位.这两个值都将在布尔上下文中求值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读