How predicates are evaluated

Discussion in 'C++' started by Gaijinco, Mar 8, 2006.

  1. Gaijinco

    Gaijinco Guest

    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){
    ...
    }
    }
     
    Gaijinco, Mar 8, 2006
    #1
    1. Advertising

  2. Gaijinco wrote:
    > 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.
    --
    <mailto:> <http://www.dietmar-kuehl.de/>
    <http://www.eai-systems.com> - Efficient Artificial Intelligence
     
    Dietmar Kuehl, Mar 8, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Alfraed
    Replies:
    0
    Views:
    826
    Alfraed
    Jul 14, 2003
  2. Martin Buchleitner
    Replies:
    6
    Views:
    28,022
    Moody
    Jul 17, 2003
  3. Soren Kuula
    Replies:
    2
    Views:
    577
    Malcolm Dew-Jones
    Apr 13, 2005
  4. Maitre Bart
    Replies:
    0
    Views:
    443
    Maitre Bart
    Oct 22, 2004
  5. Replies:
    0
    Views:
    333
Loading...

Share This Page