المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Did you know that '&' can be a logical AND operator? [modified]



C# Programming
12-05-2009, 06:50 PM
I almost lost some money today on a bet with a colleague arguing that the following Java code was just plain invalid.

if( this_thing == DING & that_thing == DONG ) {
thenGoDoTheOtherThing();
}Fortunately, he did not take me up on the bet! Turns out, for both Java and C#, when the & operator is used in this context the compiler stops treating it as the bitwise AND operator. Instead it treats it like the logical AND operator (&&) except that it applies a slightly modified evaluation rule - where && stops evaluation as soon as it encounters the first expression that evaluates to false, & goes ahead and evaluates all the expressions regardless of what each component expression evaluates to. The logical AND still works as one might expect, just that all the component expressions are always evaluated. Here's an example:

class Program
{
static void Main(string[] args)
{
if (Eval1() & Eval2())
Console.WriteLine("Eval1() and Eval2() returned true.");
else
Console.WriteLine("Eval1() and/or Eval2() returned false.");
}

static bool Eval1()
{
Console.WriteLine("Eval1");
return false;
}

static bool Eval2()
{
Console.WriteLine("Eval2");
return true;
}
}And here's the output you get.

Eval1
Eval2
Eval1() and/or Eval2() returned false.Guess you learn something new everyday! I am not sure that using this feature is such a great idea though. Thoughts?

--
gleat
http://blogorama.nerdworks.in[^ (http://blogorama.nerdworks.in)]
--

modified on Friday, December 4, 2009 3:31 PM