为什么不按位&操作员短路? [英] Why doesn't the bitwise & operator short-circuit?

查看:75
本文介绍了为什么不按位&操作员短路?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,如果左操作数是false,逻辑&&运算符就会短路,因为我们知道如果一个操作数是false,那么结果也是false.

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.

为什么按位&运算符也不会短路?如果左操作数是0,那么我们知道结果也是0.我在(C,Javascript和C#)中测试过的每种语言都会对两个操作数求值,而不是在第一个操作数之后停止.

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.

推荐答案

我猜这是因为源语言中的按位and通常通常直接转换为要由处理器执行的按位and指令.依次将其实现为硬件中一组适当数量的and门.

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.

这篇关于为什么不按位&操作员短路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆