views:

194

answers:

2

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?

+10  A: 

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
Mark Rushakoff
a good answer but missing the essential point - anybody doing this is just showing off. (and yes I know there are places where this kind of thing can be useful - but the examples given are definitely showing off)
pm100
@pm100: Obviously you wouldn't do this in "real" code. But it did apparently help the OP to understand when the right hand side of the operator is evaluated, which was the whole point.
Mark Rushakoff
+1  A: 
a && b++;    is equivalent to:  if(a) b++;

c || b--;    is equivalent to:   if(!c) b--;

but there is no point to writing these kind of expression. It doesn't compile to better code and is less readable in almost all cases even if it looks shorter.

tristopia