Which order is evaluation done

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Assume I have this expression

int extra = -2:

If (extra > 0 && productRepository.ExistQuantityInStock(Id,antal))
{
}

I assume that in this example will never the second expression be evaluated
because extra is negaive.
So could I be sure that the evaluation sequence is always from left to
right.

If I can't be sure of that I have to put an if clause before

//Tony
 
Assume I have this expression

int extra = -2:

If (extra > 0 && productRepository.ExistQuantityInStock(Id,antal))
{
}

I assume that in this example will never the second expression be
evaluated because extra is negaive.
So could I be sure that the evaluation sequence is always from left to
right.
According to MSDN http://msdn.microsoft.com/en-us/library/ms173145.aspx

Conditional AND: x && y Evaluates y only if x is true

// Anders
 
Assume I have this expression

int extra = -2:

If (extra > 0 && productRepository.ExistQuantityInStock(Id,antal))
{
}

I assume that in this example will never the second expression be
evaluated because extra is negaive.
So could I be sure that the evaluation sequence is always from left to
right.
According to MSDN http://msdn.microsoft.com/en-us/library/ms173145.aspx

Conditional AND: x && y Evaluates y only if x is true

// Anders
 
Assume I have this expression

int extra = -2:

If (extra > 0 && productRepository.ExistQuantityInStock(Id,antal))
{
}

I assume that in this example will never the second expression be
evaluated because extra is negaive.
So could I be sure that the evaluation sequence is always from left to
right.

If I can't be sure of that I have to put an if clause before

You can be sure of that.

&& is a so-called short-circuit and - it will only evaluate the
second expression if the first expression is true.

If you do not want that behavior then you can use &. On bool
expressions it evaluates both expressions and do an and (it has
a different semantic for integer types).

Arne
 
Back
Top