pixartist
pixartist

Reputation: 1155

use return value assignment within while statement

If I do this

while((e = data.IndexOf('}', at)) >= 0
      &&
      (s = data.LastIndexOf('{', at, e-1)) >= 0)

in C#, will the value of e in the second expression already have the value assigned within the while statement?

Upvotes: 2

Views: 90

Answers (3)

Luis Filipe
Luis Filipe

Reputation: 8718

You can always try it out.

Short answer: Yes

Long answer: I rather create easier to read code because that kind of programming does not optimize anything. It might be opinion-based but i strongly believe it's a best practice and provides better code maintenance.

while(e = data.IndexOf('}', at)) >= 0)
{
  s = data.LastIndexOf('{', at, e-1))
  if(s < 0)
    break;
  //do stuff
}

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125640

Yes, because you've used && operator, which evaluates left side first to check if evaluation of the right side is necessary.

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

from && Operator (C# Reference)

Upvotes: 0

David S.
David S.

Reputation: 6105

According to the spec, http://msdn.microsoft.com/en-us/library/Aa691322, evaluation is left to right:

For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i.

So yes, e will be assigned to the result of data.IndexOf('}', at), then data.LastIndexOf('{', at, e-1) will use that 'new' e.

Upvotes: 0

Related Questions