Search code examples
coperator-precedence

Why the output won't be this in the code?


#include <stdio.h>

int main(void) {
int i = -3, j = 2, k = 0, m;
m = ++i && ++j || ++k;
printf("%d %d %d %d\n",i,j,k,m);
    return 0;
}

I am trying to learn about associativity and precedence of operators in C. Here, The output comes out to be -2 3 0 1, but I think the output should be -2 3 1 1 because k is also pre-incremented. Why that won't be the answer? Thanks!


Solution

  • the || has short-circuit evaluation, which means that the right hand side gets evaluated only if the left hand side is false. In your case this doesn't happen since both i and j have values different than 0after being incremented, so the ++k doesn't get executed

    The same behavior occurs when you have a && in which the LHS expressions evaluates to false