Phonzy
Phonzy

Reputation: 31

C-Arithmetics and precedence

I'm practicing to read C-code faster but I'm struggling to understand this portion:

int a = 7, b = 3, c = 2, d;

d = (b+c >a) || a > c ? a-- : a++;

When I enter this into my program and print out integer d, I get the result of 7. But I cannot really understand why. Can somebody please explain this to me?

Upvotes: 1

Views: 65

Answers (3)

Theepag
Theepag

Reputation: 309

This is how operator precedence works in C

Step 1

d = (3 + 2 > 7) || 7 > 2 ? a-- : a++;

Step 2

d = false || true ? a-- : a++;

Step 3

d = true ? a-- : a++;

Here value of 'a' will be changed but not in this statement so value of 'a' still be 7 But if you print a in other statement it will changed as 6.

To learn more about operator precedence https://en.cppreference.com/w/c/language/operator_precedence

Upvotes: 1

John Bode
John Bode

Reputation: 123458

The expression is parsed as

d = ((b+c >a) || a > c) ? a-- : a++;

so d gets the result of either a— or a++, which is 7 in both cases. The difference is what the value of a is after the expression is evaluated.

|| forces left to right evaluation, so b+c > a is evaluated first. Since b+c is 5, the result of the expression is false (0), so a > c is evaluated. The result of that expression is true (1), so the result of (b+c > a) || a > c is true (1), meaning we assign the result of a— to d. Thus d will be 7 and a will be 6.

Upvotes: 1

Adrian Mole
Adrian Mole

Reputation: 51825

You are assigning to d the value of either a-- or a++. Both of these expressions have a value of 7 (the original value of a); the difference between the operators is what they do to their operand (a) after evaluating the expression: one then increments it and the other decrements it.

That is why they are called post-increment and post-decrement operators.

Maybe you are getting confused with the pre-increment and pre-decrement operators, which are ++a and --a? (See also: Pre increment vs Post increment in array .)

As for the ternary operator (x ? y : z) and how to 'read' that, then you can take it as if x then y else z; so, if the result of the test (which has a logical OR, which means it will be true if either comparison is true) is true, then d = a--, otherwise d = a++. But, as mentioned already, both will give the same value to d, in this case (though they will have different effects on a). Note also that the ternary operator has a lower precedence than either the logical OR or the relational comparisons, so you can read as though everything between the = and the ? is in (another set of) brackets.

Upvotes: 2

Related Questions