views:

163

answers:

1

I don't understand the following excerpt from Accelerated C++:

Starting at

Because || is left-associative, and because of the relative precedence of ||,== ,and -,

r == 0 || r == rows - 1 || c == 0 || c == cols - 1 means the same as it would if we were to place all of its subexpressions in parentheses:

((r == 0 || r == (rows - 1)) || c == 0) || c == (cols - 1)

and going until

Otherwise, it does something else, which we must now define.

I don't understand this. How would you tell me the same with your own words?

+5  A: 

If you have a series of conditions you want to evaluate, let's say "if x is 1 or y is 2, then call function foo()" then there is no point in performing the second test (y is 2) if you already know that x is 1. The || operator works like that:

i( x == 1 || y == 2 ) {
     foo();
}

The expression y == 2 will not be evaluated if x == 1, because it is not necessary. This is called short circuited evaluation, and can save a lot of time if evaluation is expensive.

If this isn't what you are asking about, please make your question more explicit.

anon
I think you should also point out that this means that any computation performed in the second expression is not going to happen if the first expression evaluates to true as this can lead to confusing errors. Or am I mistaken?
pmr
I thought that was what I was saying|
anon
I was thinking about something like x == 1 || ++y == 2. If x equals 1 y won't be incremented.
pmr
When I said the second expression will not be evaluated, that's what I meant. That's what evaluating an expression means in C++.
anon
Does the whole section starting where I said and going until where I said (there are things in between and I'm talking about them too) mean just that?
Delirium tremens
+1 you bring it to the point. For a Haskel programmer it is the de facto behavior (called lazy evaluation)
Burkhard
@Delurium I would say so - others may find more in it.
anon