Why not bitwise & short circuit operator?

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

Why is the bitwise operator & not closing too? If the left operand is 0 , then we know that the result is also 0 . Each language I tested this in (C, Javascript, C #) evaluates both operands instead of stopping after the first.

Is there a reason why it would be a bad idea to let the & operator short-circuit? If not, why don't most languages ​​do short quotes? This seems like an obvious optimization.

+6
source share
5 answers

I would suggest, because bitwise and in the source language usually gets a fairly direct relation to the bitwise instruction and , which must be executed by the processor. This, in turn, is implemented as a group of the correct number of gates and in equipment.

I do not see this in most cases optimizing a lot. Evaluating a second operand will cost less than testing to see if it should be evaluated.

+9
source

Short circuit is not an optimization device. This is a flow control device. If you do not have a short circuit p != NULL && *p != 0 , you will not get a slower program, you will get an emergency program.

This type of short circuit almost never makes sense for bitwise operators and is more expensive than a regular short circuit operator.

+7
source

Bitwise operations are usually so cheap that checking will make the operation twice as long or larger, while the gain of the short circuit of the logical operator is potentially very large.

+2
source

If the compiler should give a check for both operands, and I assume that you will be much slower in any NORMAL state.

+2
source

For the same reason that * does not close to closure, if the first operand is 0 - this would be an unclear special case, and adding special run-time tests for it would make all multiplications slower.

When the operands are not constants, a short circuit is more expensive than a short circuit, so you do not want to do this unless the programmer explicitly requests it. Therefore, you really want to have clean and simple rules regarding when this happens.

+1
source

Source: https://habr.com/ru/post/910616/


All Articles