Sunday, July 31, 2005

& and && in C# , part - I

There are 2 AND,OR operators in C# ( of course it exists in language like C++ or Java as well ), one is &, | and second one is &&, II , most of the time we work with the second one, first one is less popular in regualar programming, but the first one is more powerfull and usefull than the second one( my personal comments :) ).
As per MSDN documentation difference between them two is following ...

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.
Binary & operators are predefined for the integral types and bool. For integral types, & computes the bitwise AND of its operands. For bool operands, & computes the logical AND of its operands; that is, the result is true if and only if both its operands are true.

The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true.
The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false.
Let me use the following code to explain it ....
int i = 0;
int j = 0;
if( false & ( ++i > 0 ) )
{
MessageBox.Show( "Inside if condition" );
}
if( false && ( ++j > 0) )
{
MessageBox.Show( "Inside if condition" );
}
MessageBox.Show( i.ToString() );
MessageBox.Show( j.ToString() );
guess what will be the value of i and j when MessageBox will show ... i will be 1 and j will be 0, since first if has used & so run time will evaluate both the operand( hence i will be increased by 1), but in case && as the first oeprand is FALSE it will not evaluate the scond one at all( hence value of j will remain 0 ), but none of them will show "Inside if condition".
I will write some more interesting facts of & operator in part II.

Note : in C++ we can use & as a unery operator. & gives the address of the operand.

1 comment:

Hirushan said...

Thanks nice post!