operator precedence

Quick question about operator precedence. The arithmetic operator has higher precedence than comparison and comparison has higher precedence than the logical operator. So in the below example, lim-1 is evaluted first. Then < is evaluated next. So now that expression returns 1 or 0. Now shoudn't (c=getchar()) != '\n' be evaluated before the && separating the two expressions? If that's true, then that doesn't make sense either, because why would it check for a char from input if we already know it exceeded the limit? If it is not true, then why are we evaluating && before (c=getchar()) when the latter has higher precedence than &&?

for (i=0; i < lim-1 && (c=getchar()) != '\n' && c != EOF; ++i)
http://www.cplusplus.com/doc/tutorial/operators/#precedence

1
2
3
(i < lim-1) &&
((c=getchar()) != '\n') &&
(c != EOF)


Note that && is lazy. The "chain" will be broken as soon as it can.
For example if (i < lim-1) is false, then the next two conditions will not be checked.
Last edited on
In this line:

for (i=0; i < lim-1 && (c=getchar()) != '\n' && c != EOF; ++i)

The primary Expression Operators () has highest precedence which encloses c=getchar(). So why is that not evaluated before i < lim-1?
Don't confuse operator precedence with the order in which things are evaluated.

The precedence rules are there so that you don't have to write parenthesis all over the place to make things unambiguous. I mean you don't have to write this: ((1*2)+1)+(x*5)) You can just write it like this: 1*2+1+x*5, but without the precedence rules it wouldn't be clear if you meant (((1*(2+1))+x)*5), ((1*2)+((1+x)*5)) or something else.

If you have an expression 2*x+3*y then the precedence rules say it should be evaluated as (2*x)+(3*y) so we will obviously have to calculate the two multiplications before we can calculate the sum. On the other hand it is not clear if (2*x) or (3*y) should be calculated first. It's up to the compiler to decide.

Some operators, like the && operator, have more strict rules about the order in which the sub-expressions should be evaluated. The && operator first evaluates the first operand and only if it is true the second operand is evaluated.
Last edited on
Topic archived. No new replies allowed.