5

if I have the following bool:

bool success = true;

Will the following three lines of code store the same results in success:

1 - success &= SomeFunctionReturningABool();

2 - success = success & SomeFunctionReturningABool();

3 - success = success && SomeFunctionReturningABool();

I found an article stating that 1 is a shortcut for 2 - but is 2 the same as 3 or is my application going to explode on execution of this line...

4 Answers 4

8

For boolean type, single & evaluates all operands, while double && only evaluates while necessary (i.e. if the first operand is false, it won't bother to evaluate the second one), also known as "short-circuit" evaluation.

Source: http://msdn.microsoft.com/en-us/library/2a723cdk(v=vs.80).aspx

As for the &= assignment operator, it works same as single &.

Sign up to request clarification or add additional context in comments.

1 Comment

Great thanks! so that would mean that if success was false the 3rd line would not execute the function?
2

1 and 2 are the same in the same way that the following are the same:

int value += 1;
int value = value + 1;

3 is not the same, as if success is false, SomeFunctionReturningABool() won't get called - which is not what you want.

Comments

0

You are right. 1 is a shortcut to 2. The difference between '&' and '&&' you can find here msdn

'&' is a logical AND while '&&' is conditional AND

Comments

-1

Options 2 and 3 are equivalent, and &= does exactly that.

You should know that if the first call fails, the subsequent calls might not occur: for example,

if (x != null && x.Test() == true)

It evaluates x != null first - and if it's false then the second part won't get executed. The same may apply here.

(Huh, I wonder if that's just for && and not &...)

1 Comment

No, 2 and 3 are NOT equivalent. The single ampersand would actually evaluate BOTH arguments, unlike, as you noted, the double ampersand. See msdn.microsoft.com/en-us/library/2a723cdk(v=vs.80).aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.