Reputation: 74
main()
{
int i=-3, j=2;
int m = ++i || ++j;
printf("%d %d",i,j);
}
if prefix increment operator has right to left associativity then ++j should execute first. But here only ++i executes and ++j doesn't. Why?
Upvotes: 0
Views: 677
Reputation: 836
Your observation is not related to operator associativity, but to the definition of the execution order of binary logical operators.
You're using ++j as the second operator of a logical operation. In C, binary logical operators have an "early exit", that is, execution stops whenever further execution won't change the result anymore. This is the case when the left operand of || evaluates to TRUE, or the left operand of && evaluates to FALSE. In the former case, the result is TRUE, whatever the other operands yield. In the latter case, it's FALSE, and further evaluation won't change that.
This language feature is very important if you have functions as operands of logical operators. It guarantees that the functions are called in the specified order, and only those functions are evaluated that contribute to the result.
In your example, you evaluate:
int m = ++i || ++j;
Since i == -3, ++i yields -2, which is not 0, hence interpreted as TRUE. So the evaluation of || stops here, and j is not touched.
Upvotes: 5
Reputation: 392
You are wrong postfix increment operator has left to right associativity.
If you still have doubt do check this link:http://en.cppreference.com/w/cpp/language/operator_precedence
EDIT:
Prefix operators have right to left associativity but precedence and associativity don't tell you about order of evaluation. They only tell you about grouping. For example, precedence is what tells use that ab+c is grouped as (ab)+c instead of a*(b+c). The compiler is free to evaluate a, b and c in any order it sees fit with either of those expressions. Associativity tells you about grouping when you have operators of the same precedence, most often, the same operators. For example, it's what tells you that a-b-c is equivalent to (a-b)-c, not a-(b-c) (otherwise stated, subtraction is left associative).
Order of evaluation is defined by sequence points. There's a sequence point at the end of a full expression (among other things). At the sequence point, all the previous evaluations have to have taken place, and none of the subsequent evaluations can have taken place yet.
Upvotes: 3