Search code examples
clogical-operatorsoperator-precedence

Require explanation for the output


Code:

#include<stdio.h>
int main()
{
    int j = 7, i = 4;
    j = j || ++i && printf("you can");
    printf("%d %d",i,j);
    return 0;
}

Output: 4 1

[Code Link][1]

  1. The precedence of prefix operator is higher than logical operators. 2.Logical && has higher precedence than logical ||.
  2. In Logical AND(&&) if first operand evaluates to false than second will not be evaluated and In Logical OR(||) if first operand evaluates to true, then second will not be evaluated.
  3. The complete expression is evaluating to true, therefore j is 1 .

Doubts:

  1. Why the first rule is not followed here? Shouldn't it be correct?

    j=(j||((++i) &&printf("you can")));
    

Therefore value of i becomes 5, in the printf statement.

Why are the general precedence rules are violated here? Associativity comes into action when precedence of two operators is same. Shouldn't the compiler first see whether to evaluate || or &&?

If || is evaluated first, which shouldn't be as per my knowledge, then result is correct. However, if it is not evaluated first, then you can51 should be printed.


Solution

  • In this expression:

    j = j || ++i && printf("you can");
    

    There's a sequence point after the || and it is evaluated from left to right. Since j is non-zero, the rest of the expression is not evaluated. Hence, j || (....) becomes true which is 1. Since is ++i is not evaluated i remains 4. Hence, the output is 4, 1.

    From the C standard:

    Annex C

    — The end of the first operand of the following operators: logical AND && (6.5.13); logical OR || (6.5.14); conditional ? (6.5.15); comma , (6.5.17).

    If you j was zero then ++i && printf("you can") would have been evaluated and i would become 5 and you can will also be printed. You are correct about the precedence of ++ being greater than ||, but since there's a sequence point, j|| is evalauted first.