gpt4 book ai didi

c++ - boolean 技巧的比较运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:34:48 26 4
gpt4 key购买 nike

在 C++ 中,逻辑运算符 && , || , !有没有,对应连词 , 析取 , 否定 , 分别。

但我注意到比较运算符 == , != , < , > , <= , >=也可以用于 boolean 值!鉴于 PQ是 boolean 值:

P == Q是双条件的 ,

P != Q是排他析取 ,

P < Q是逆非蕴涵 ,

P > Q是非暗示 ,

P <= Q是蕴涵 ,

P >= Q是逆蕴 .

我的问题是:

  1. 程序会通过这个技巧表现得更好吗?

  2. 是否有任何使用此技巧的示例代码(任何语言)?

最佳答案

Will the performance increase by this trick?

在任何处理器上,当 P 时,它会有任何好处。和 Q是简单的变量,这将足够简单,您应该期望编译器已经使用它而无需重写任何源代码。

但请记住 P < Q总的来说比 !P && Q 有明显的缺点 : 它需要评估 Q , 当结果已知时 P评估为 true .这同样适用于所有其他关系运算符。

Is there any example code using this trick (in any language)?

不是把戏,而是因为可以说它会导致代码更容易理解(不是任何特定语言):

if ((a == null) != (b == null))
throw "a and b must either both be null, or both be non-null";

可以写成^ .哪个更容易阅读是一个见仁见智的问题。

关于c++ - boolean 技巧的比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40069217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com