开发者

XOR: are these two equivalent?

开发者 https://www.devze.com 2023-04-05 17:29 出处:网络
I saw this piece of code in the underscore.js source: if ((!a && b) || (a && !b)) r开发者_Go百科eturn false;

I saw this piece of code in the underscore.js source:

if ((!a && b) || (a && !b)) r开发者_Go百科eturn false;

Is that equivalent to the following?

if (a ^ b) return false;


Strictly speaking, no. && and || are logical operators, whereas ^ is a bit-wise operator.

But if your inputs are booleans (or integers from the set {0, 1}), then the semantics will be basically the same. If you can't guarantee these inputs, you can still ensure identical semantics thus:

if (!a ^ !b) return false;

(Assuming, of course, that a and b are plain variables, not complex expressions with side-effects.)


Those two are not the same because a ^ b is a bitwise xor function instead of a logical xor function. So, if a = 1 and b = 2, then a ^ b=3 but you would want a falsy value because both a and b are truthy.

0

精彩评论

暂无评论...
验证码 换一张
取 消