为什么会出现在Java和C#的逻辑和位运算符之间的区别? [英] Why is there a distinction between logical and bitwise operators in Java and C#?

查看:241
本文介绍了为什么会出现在Java和C#的逻辑和位运算符之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

像即Java和C#语言兼得位运算和逻辑运算。



逻辑运算符只作布尔运算,位运算符与整型工作,以及感。由于C没有布尔类型,并且对所有非零整数为真,逻辑和位运算符的存在是有意义的存在。然而,如Java或C#语言有一个boolean类型,因此编译器可以自动使用正确的运营商,这取决于类型的上下文。



那么,有没有一些具体的之所以在这些语言有逻辑和位运算符?还是他们只是包括了熟悉的原因呢?



(据我所知,您可以使用按位运营商在布尔环境中规避Java中的短路和C#中,但我从来没有需要这样的行为,所以我想它可能是一个主要是未使用的特殊情况下)


解决方案
$ b ?$ b

1)有在这些语言有逻辑和位运算符的一些具体原因




是:




  • 我们必须布尔运算符做布尔逻辑(布尔值)。

  • 我们有位运算符做按位逻辑(整数值)。




2)据我所知,您可以使用按位运营商在布尔上下文规避短路Java和C#,




有关至于C#的推移这根本不是真的。结果
C#有例如2布尔AND运算符:&安培; (完全)和&放大器;&安培; (短),但它不允许在布尔位操作。



所以,真的是合乎逻辑和按位运算符之间不存在重叠或裁员。两者不适用于同一类型。


Languages like i.e. Java and C# have both bitwise and logical operators.

Logical operators make only sense with boolean operands, bitwise operators work with integer types as well. Since C had no boolean type and treats all non-zero integers as true, the existence of both logical and bitwise operators makes sense there. However, languages like Java or C# have a boolean type so the compiler could automatically use the right kind of operators, depending on the type context.

So, is there some concrete reason for having both logical and bitwise operators in those languages? Or were they just included for familiarity reasons?

(I am aware that you can use the "bitwise" operators in a boolean context to circumvent the short-circuiting in Java and C#, but i have never needed such a behaviour, so i guess it might be a mostly unused special case)

解决方案

1) is there some concrete reason for having both logical and bitwise operators in those languages?

Yes:

  • We have boolean operators to do boolean logic (on boolean values).
  • We have bitwise operators to do bitwise logic (on integer values).

2) I am aware that you can use the "bitwise" operators in a boolean context to circumvent the short-circuiting in Java and C#,

For as far as C# goes this simply is not true.
C# has for example 2 boolean AND operators: & (full) and && (short) but it does not allow bitwise operations on booleans.

So, there really is no 'overlap' or redundancy between logical and bitwise operators. The two do not apply to the same types.

这篇关于为什么会出现在Java和C#的逻辑和位运算符之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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