Search code examples
cboolean-operations

Variables combined with && and ||


What do the last lines mean?

a=0;
b=0;
c=0;

a && b++;
c || b--;

Can you vary this question to explain with more interesting example?


Solution

  • For the example you gave: if a is nonzero, increment b; If c is zero, decrement b.

    Due to the rules of short-circuiting evaluation, that is.

    You could also test this out with a function as the right-hand-side argument; printf will be good for this since it gives us easily observable output.

    #include <stdio.h>
    int main()
    {
        if (0 && printf("RHS of 0-and\n"))
        {
        }
    
        if (1 && printf("RHS of 1-and\n"))
        {
        }
    
        if (0 || printf("RHS of 0-or\n"))
        {
        }
    
        if (1 || printf("RHS of 1-or\n"))
        {
        }
    
        return 0;
    }
    

    Output:

    RHS of 1-and
    RHS of 0-or