Monday, July 18, 2011

boolean vs logical operators

This is a subject that has never been entirely clear in my mind.  What is the difference between boolean and logical operators?

Well, it can be subtle.  With a boolean you can perform "and" operations and you can also use "and" as a logical operator.  The results of both types of operations are frequently used in a similar fashion.

A boolean AND essential tests two boolean statements and returns true if both are true.

A logical AND typically takes two (or more) bytes or words and through the action of comparison returns a value of the same type with all one bits set where bits of both operands are one, and zeros corresonding bits are not the same.

In C# the boolean operator for AND is && while the logical operator for AND is &.  The use of similar symbols tends to add to the confusion.

It seems obvious that true && true == true.  Is it also true that true & true is true?

This code demonstrates that the answer is yes!

if (true && true)
 Console.WriteLine("\n{0} and {1} == {2}", true, true, true && true);

if (true & true)
 Console.WriteLine("\ntrue & true = {0}", true & true);

Try it.

No comments:

Post a Comment