How predicates are evaluated

G

Gaijinco

If I have something like:

if (dx<0 and dy>=SIZE and m[dx][dy]!=0){
...
}

Can I assume that m[dx][dy]!=0 would be testes last or to be sure I
need to nest it?

if (dx<0 and dy>=SIZE){
if (m[dx][dy]!=0){
...
}
}
 
D

Dietmar Kuehl

Gaijinco said:
if (dx<0 and dy>=SIZE and m[dx][dy]!=0){
...
}

The built-in short-circuit operators ('||' aka 'or' and '&&' aka 'and')
are evaluated from left to right and stop evaluating as soon as the
result of the expression is determined. The same does *not* apply to
user defined operators whose operands are evaluated in some order.
Can I assume that m[dx][dy]!=0 would be testes last or to be sure I
need to nest it?

It depends on what the result type of the other involved operations
is and whether there is an overload for one of the logical operators
involving these types. In usual contexts you can normally ignore the
possibility of overloaded operators but in template code you should
play safe, i.e. make sure that the built-in operators are used, e.g.:

if (bool(dx < 0) and bool(dy >= SIZE) and bool(m[dx][dy] != 0))
...

Of course, the above expression assumes that 'm' is a suitably offset
pointer such that a negative index is allowed at all.
 

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

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top