如果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的位表示,即具有最低有效位零的所有位.这两个值都将在布尔上下文中求值.
原文地址:https://www.jb51.cc/c/115559.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。