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

Confusion regarding precedence of C operators

I"m quite confused about the following block of code:

int a = 1, b = 2, c = 3;

printf("%d ", c - 3 && b++ > c);

printf("%d %d %d", a, b, c);

Initially, I thought that the output would be 0 1 3 3 since b would become 3 due to the side effect of the post-fix operator. But, the output I am getting is 0 1 2 3. Why is this?

Specifically, to evaluate c - 3 && b++ > c I used the C operator precedence table (https://en.cppreference.com/w/c/language/operator_precedence#cite_note-1) to determine the operator precedence. Postfix increment operator has much higher precendence than the logical AND operator. So why is the output the way it is? Do logical operators somehow bypass operator precedence in C?

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 dictates how operands are grouped, not the order in which they are evaluated. So this:

c - 3 && b++ > c

Parses as this:

(c - 3) && ((b++) > c)

The logical operators && and || have what’s referred to as short circuit behavior, which means if the result can be determined from just the left operand then the right operand is not evaluated.

The left operand of && is c - 3. This evaluates to 0, which means the entire && expression evaluates to 0 and the right operand, i.e. b++ > c is not evaluated, so b is not incremented.

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