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

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

概述如果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 guarante 如果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 – 在布尔值上使用按位不是运算符(〜)调用未定义的行为?全部内容,希望文章能够帮你解决c – 在布尔值上使用按位不是运算符(〜)调用未定义的行为?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1233287.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存