简体   繁体   English

将&&(逻辑和)运算符转换为|| (逻辑或)运算符

[英]Converting && (logical and) operator into || (logical or) operator

bool a, b; 布尔a,b;

A)
if (a && b)
    return true;
else
    return false;

B)
if (!a || !b)
    return false;
else
    return true;

I am little bit confused. 我有点困惑。 Are A & B equivalent?? A和B等价吗?

Yes, they are equivalent, because of De Morgan's laws: 是的,由于De Morgan的法律,它们是等效的:

!(a && b) == !a || !b

hence 因此

 (a && b) == !(!a || !b)

However, at any decent company, one would get fired quickly if one wrote code like this. 但是,在任何一家像样的公司中,如果有人编写这样的代码,就会很快被解雇。

if (<condition>)
    return true;
else
    return false;

is redundant, and it's more readable to write 是多余的,并且编写起来更具可读性

return <condition>;

instead. 代替。 (maybe return <condition> != 0 if you need to always ensure a 0 or 1 result, but this is already the case in your code, since && and || are guaranteed to yield 0 or 1.) (如果需要始终确保结果为0或1,则可能return <condition> != 0 ,但是在代码中已经是这种情况,因为&&||保证得出0或1。)

Yes they are. 对,他们是。 The first one is simply checking if both of them are true, and the second one checks if either of them are false. 第一个简单地检查它们是否都为真,第二个简单地检查它们是否都为假。 Both of them still return true if both are true, and false if not. 如果两者都为true,则两者仍返回true;否则为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM