Click to See Complete Forum and Search --> : Logical operators


May 1st, 2000, 04:42 PM
Hi
The following demonstrates that bitwise & and | work similar to logical AND(&&) and logical OR(||).

bitwise &
(true & true):true
(true & false):false
(false & true):false
(false & false):false

bitwise |
(true | true):true
(true | false):true
(false | true):true
(false | false):false

Then, why do we have logical AND and OR?

dogbear
May 2nd, 2000, 10:57 AM
WhoeverYouAre,

Bitwise operators are used to manipulate bits within a given value.
For example:char x = 10; // x now holds the value 0000 0000 0000 1010
if ( x & 1 != 0 )
...


The if statement gets the value of x and does a bitwise & operation on it...
0000 0000 0000 1010 - the value of x
& 0000 0000 0000 0001 - the value 1
---------------------
0000 0000 0000 0000


As you can see, the resulting value is 0, so the if statement is FALSE.

If we bitwise OR the two values:if ( x | 1 != 0 )
...


...the following occurs: 0000 0000 0000 1010 - the value of x
| 0000 0000 0000 0001 - the value 1
---------------------
0000 0000 0000 1011

The resulting value is 11, a non-zero number, therefore TRUE.

Logical operators, on the other hand, do not deal with bits at all.
They deal with the entire expression.
For example:int x = 10;
int y = 23;
if ( x == 10 && y == 21 )
...

This if statement looks at each side of the && operator separately.
Is x equal to 10? Yes.
Is y equal to 21? No.
A yes AND a no equals NO!
The entire expression is FALSE.

If we do a logical OR operation on it instead...if ( x == 10 || y == 21 )
...

...we get
Is x equal to 10? Yes.
Is y equal to 21? No.
A yes OR a no equals YES!
The if statement is therefore TRUE.

If you really want to understand this fully, the best way
is to keep practicing on paper. Otherwise, to answer your
question, the bitwise operators are to manipulate a value while
the logical operators manipulate an entire expression.

Hope this hasn't confused you more.

Regards,
dogBear