Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a distinction between logical and bitwise operators in Java and C#?

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)

like image 871
Askaga Avatar asked Jan 01 '13 20:01

Askaga


1 Answers

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.

like image 190
Henk Holterman Avatar answered Oct 18 '22 08:10

Henk Holterman