1

Here is my code.

#include <stdio.h>

#define PRINT3(x,y,z) printf("x=%d\ty=%d\tz=%d\n",x,y,z)

int main()
{
    int x,y,z;

    x = y = z = 1;
    ++x || ++y && ++z; PRINT3(x,y,z);

    return 0;
}

The output is,

x=2     y=1     z=1

I don't understand how this happens. What I would expect is, since ++ has higher precedence than && or ||, the prefix operations here will get evaluated first. That is, ++x, ++y and ++z will get evaluated first. So the output I expected was,

x=2     y=2     z=2

Could someone help me understand please? Thanks in advance.

I looked at this question, but I still don't understand why the compiler decides to evaluate || before evaluating all the ++s. Is this compiler dependent, or is it defined in the standard that whenever an operand of || is 1, it should be evaluated before evaluating other higher precedence operations in the other operand.

Community
  • 1
  • 1
jacare
  • 13
  • 3

3 Answers3

2

If the first operand of || is true. At run time the rest of the expressions are not evaluated. Because irrespective of whatever the result of remaining portion the answer is going to be true. Hence you are getting the expected result.

Mohammad Sadiq
  • 5,070
  • 28
  • 29
1

Higher precedence of an operator doesn't guarantee that it will be evaluated first but it guarantees that the operands will be binds (parenthesize) to it first.

++x || ++y && ++z;

will be parenthesize as

( (++x) || ( (++y) && (++z) ) );  

Since || operator guarantees the evaluation of its operand from left-to-right, (++x) will be evaluated first. Due to its short circuit behavior on becoming left operand true, right operand will not be evaluated.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • Yeah, I checked the C standard. 6.5.14. || will be evaluated from left to right. What is the mechanics of the compiler making sure that this happens? I mean, how does the compiler parse the expression to make sure that the left side of || gets evaluated first? – jacare Feb 16 '15 at 15:21
  • First phase of compiler read program character by character and generate tokens. Operators are also token. When compiler find these operators then it look up for their operands in look up table. In look up table there also stored information about operators like about its associativity, precedence, order of evaluation of its operands. Compiler use this information to evaluate the operands. I have given a *rough* idea. Actual mechanism is complex. – haccks Feb 16 '15 at 15:33
1

Here, The compiler does a bit of optimization.

Anything OR'ed with a "1" will always be 1. And similarly, anything AND'ed with a "1" will be 0.

The compiler will skip code block based on these evaluations.

In your case,

++x || ++y && ++z

Here x > 0. So no matter what you OR it with, the result will be true.

Hence, the compiler simply skips evaluating the rest of it.

For further information, Google for "short circuit evaluation."

Stark07
  • 468
  • 8
  • 17