Which order is evaluation done

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
 
A

Anders Eriksson

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
 
A

Anders Eriksson

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
 
A

Arne Vajhøj

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
 

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

Top