Difference in && and &=

J

Joel

Run this method:

public void test()
{
bool b;
int i=0;

b=false;
i=0;
b=(b && i++==1);
Console.WriteLine(i.ToString());

b=false;
i=0;
b&=i++==1;
Console.WriteLine(i.ToString());
}

Notice how in the first syntax, i++ is NOT evaluated (because of
short-circuit evaluation) but in the second syntax i++ is evaluated. I
wonder if this was intentional or an oversight. It burned me in a situation
when I was counting on short-circuit evaluation.

<joel>
 
C

Chris R. Timmons

Run this method:

public void test()
{
bool b;
int i=0;

b=false;
i=0;
b=(b && i++==1);
Console.WriteLine(i.ToString());

b=false;
i=0;
b&=i++==1;
Console.WriteLine(i.ToString());
}

Notice how in the first syntax, i++ is NOT evaluated (because of
short-circuit evaluation) but in the second syntax i++ is
evaluated. I wonder if this was intentional or an oversight. It
burned me in a situation when I was counting on short-circuit
evaluation.

Joel,

& and && are two completely different operators. & performs a
bitwise "and" of two numbers, but && is the boolean "and" operator.
Change the && to & and both code blocks return the same result (1).
 
X

Xarky

Chris R. Timmons said:
Joel,

& and && are two completely different operators. & performs a
bitwise "and" of two numbers, but && is the boolean "and" operator.
Change the && to & and both code blocks return the same result (1).


Is short-circuit evaluation the same as lazy evaluation?
 
J

Joel

Yeah, I'm aware of the difference between & and && (and and and? ;-). Just
pointing out a 'gotcha' that 'gotme'.

</joel>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top