MONUDDIN TAMBOLI
MONUDDIN TAMBOLI

Reputation: 152

How is precedence working in C for this expression

I am using C programming modern approach Precedence for '||' operator is 13 and for increment(prefix) is 2 in table how his code is working

int i = 3, j = 4,k = 5;
printf("\n%d",i < j || ++j < k);
printf("\n%d %d %d",i,j,k);
output:1 
3 4 5

Yes it is short-circuit and if left side is 0 then only it will go for right side of OR i found that answer while searching but when this question come what i did was simply go search for precedence table check it and solve it as prefix have high precedence j should increment first as it have highest precedence. Why it does not follow according to precedence or what is my mistake while trying to solve it? when expression like this are there without braces we should use precedence correct or not?

Upvotes: 0

Views: 112

Answers (3)

dbush
dbush

Reputation: 223689

You're confusing the difference between operator precedence and order of evaluation.

Operator precedence dictates which operands the operators are grouped with. Order of evaluation dictates when each subexpression is executed.

In your case:

i < j || ++j < k

The operators are effectively grouped as follows:

(i < j) || ((++j) < k)

Only the || operator dictates the order in which its operands are evaluated. The others do not. This means that i < j must be evaluated before (and if) ++j < k is evaluated, regardless of what the right-hand side of || contains.

As an example of order of evaluation, suppose you had this expression:

f() + g() * h()

The functions f, g, and h may be called in any order. Just because g() * h() has to be evaluated before the addition is evaluated doesn't mean that f won't be called first.

Upvotes: 3

aschepler
aschepler

Reputation: 72271

Precedence is not order of evaluation. Precedence only determines which expressions go with other expressions and operators, essentially adding implied parentheses.

In this example, operator precedence helps us determine that

i < j || ++j < k

means the same as

(i < j) || ((++j) < k)

Then, the individual operators (sometimes) have rules about the order of evaluation. This expression is a use of the || operator on two subexpressions i < j and ++j < k. So per the || rules, the left operand is evaluated first. If its result is not zero, nothing within the right operand is evaluated at all.

Upvotes: 3

Thomas Jager
Thomas Jager

Reputation: 5265

In an operator precedence table, the lower the number, the more tightly it binds its operands.

The expression i < j || ++j < k can be written as (i < j) || ((++j) < k).

Precedence doesn't tell you the order in which things happen, it tells you how to group things. From (i < j) || ((++j) < k), the operator || evaluates the left side first. If it's true, the right side never gets executed. The fact that ++ has a high precedence doesn't change the behaviour of ||.

Upvotes: 4

Related Questions