Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How are logical expressions that include increment and decrement operators evaluated in C?

int a = 0, b= 1, c = 1;
if (c-- || ++a && b--)

I know that the precedence for && is the highest here. So what happens? Does it start from && and then looks at the expression on its left which is (c– || ++a) and evaluates that first?

I have been experimenting for a while with different expressions and I just can’t wrap my head around it. Thanks in advance.

Edit: I would have used parenthesis if I could but this is a uni question so I don’t really have a say

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Operator precedence does not directly influence evaluation order. What it does do is dictate how operands are groups. And since && has higher precedence than || as you noted, your expression is equivalent to:

(c-- || (++a && b--))

Given that the && operator uses short circuit evaluation, ++a would be evaluated before ++b. However, the entire subexpression ++a && b-- is the right side of the || operator which also uses short circuit evaluation, which means the left side, i.e. c-- would get evaluated first.

Since c-- evaluates to 1, the right side of the || operator, i.e. ++a && b--, is not evaluated. So c gets decremented and a and b are left unchanged.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading