Why doesn't the bitwise & operator short-circuit?

寵の児 提交于 2019-12-19 18:23:53

问题


We all know that the logical && operator short circuits if the left operand is false, because we know that if one operand is false, then the result is also false.

Why doesn't the bitwise & operator also short-circuit? If the left operand is 0, then we know that the result is also 0. Every language I've tested this in (C, Javascript, C#) evaluates both operands instead of stopping after the first.

Is there any reason why it would be a bad idea the let the & operator short-circuit? If not, why don't most languages make it short-cicuit? It seems like an obvious optimization.


回答1:


I'd guess it's because a bitwise and in the source language typically gets translated fairly directly to a bitwise and instruction to be executed by the processor. That, in turn, is implemented as a group of the proper number of and gates in the hardware.

I don't see this as optimizing much of anything in most cases. Evaluating the second operand will normally cost less than testing to see whether you should evaluate it.




回答2:


Short-circuiting is not an optimization device. It is a control flow device. If you fail to short-circuit p != NULL && *p != 0, you will not get a marginally slower program, you will get a crashing program.

This kind of short-circuiting almost never makes sense for bitwise operators, and is more expensive than normal non-short-circuiting operator.




回答3:


Bitwise operations are usually so cheap that the check would make the operation twice as long or more, whereas the gain from short-circuiting a logical operator is potentially very great.




回答4:


If the compiler has to emit a check for both operands of & I guess that you it'll be much slower in any NORMAL condition.




回答5:


For the same reason that * does not short-circuit if the first operand is 0 -- it would be an obscure special case and adding special runtime tests for it would make all multiplies slower.

When the operands are not constants, short circuiting is more expensive than not short circuiting, so you don't want to do it unless the programmer explicitly requests it. So you really want to have clean and simple rules as to when it occurs.



来源:https://stackoverflow.com/questions/9688343/why-doesnt-the-bitwise-operator-short-circuit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!