Search code examples
coperator-precedenceturbo-c

Problem with operator precedence


The O/p comes out to be x=2,y=1,z=1 which doesnt agree with the operator precedence. I was running this on Turbo c++ compiler:

void main()
{
    int x,y,z,q;
    x=y=z=1;
    q=++x || ++y && ++z;
    printf("x=%d y=%d z=%d",x,y,z);
}

Solution

  • Operator precedence does not in any way determine the order in which the operators are executed. Operator precedence only defines the grouping between operators and their operands. In your case, operator precedence says that the expression

    q = ++x || ++y && ++z
    

    is grouped as

    q = ((++x) || ((++y) && (++z)))
    

    The rest has absolutely nothing to do with operator precedence at all.

    The rest is determined by the semantics of each specific operator. The top-level operator in this case is ||. The specific property of || operator is that it always evaluates its left-hand side first. And if the left-hand size turns out to be non-zero, then it does not even attempt to evaluate the right-hand side.

    This is exactly what happens in your case. The left-hand side is ++x and it evaluates to a non-zero value. This means that your whole expression with the given initial values is functionally equivalent to a mere

    q = (++x != 0)
    

    The right-hand side of || operator is not even touched.