Search code examples
clogical-operatorsarithmetic-expressions

Confusion with post increment and logical operator?


    #include <stdio.h>
    #include <string.h>

    main()
    {
         int i=-1, j=-1, k=0, l=2,m;
         m = i++&&j++&&k++||l++;
         printf("%d%d%d%d%d", i, j, k, l, m);
    }

Output:

00131

I am confused how the expression is getting evaluated.


Solution

  • All that really matters here is the ||. Since l++ evaluates to the boolean 1 (true), the entire statement is true. So m is 1, and the rest are just their original values plus one for the post increment after they are evaluated.

    You're evaluating the boolean expression:

    ((-1 && -1) && 0) || 2
    

    As an aside, your definition of main should be:

    int main(void)