Search code examples
clogical-operatorsshort-circuitinglogical-orlogical-and

A specific short-circuiting example in C


I understand the basic concept of short-circuiting with operators, but why does

int i = 0, j = -1, k = 1, m;
m = !(i++ && ++j) || ++k;
printf("%d %d %d %d", i, j, k, m);

have 1 -1 1 1 as an output? Specifically, why is j == -1 instead of 0?

I know similar questions have been already asked, but I don't understand this specific example which I didn't find anywhere.


Solution

  • i = -1;
    i++;         // value of expression is -1
                 // side effect is changing i to 0
    if (i++) ;   // value of `i++` is zero; the if will not "trigger"
    
    i = 0;
    if (i++ && foo) ; // i++ has value of zero (false)
                      // so false && <anything> is false
                      // so foo is not evaluated