您的位置:首页 > 其它

&和&&区别

2017-06-27 08:04 148 查看
& <– verifies both operands

&& <– stops evaluating if the first operand evaluates to false since the result will be false

(x != 0) & (1/x > 1) <– this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) && (1/x > 1) <– this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won’t throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

EDIT:

exprA | exprB <– this means evaluate exprA then evaluate exprB then do the |.

exprA || exprB <– this means evaluate exprA and only if this is false then evaluate exprB and do the ||.

It depends on the type of the arguments…

For integer arguments, the single ampersand (“&”)is the “bit-wise AND” operator. The double ampersand (“&&”) is not defined for anything but two boolean arguments.

For boolean arguments, the single ampersand constitutes the (unconditional) “logical AND” operator while the double ampersand (“&&”) is the “conditional logical AND” operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.

For all other argument types and combinations, a compile-time error should occur

参考资料

Difference between & and &&
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: