Variables combined with && and ||
What do the last lines mean?
a=0;
b=0;
c=0;
a && b++;
c || b--;
Can you vary t开发者_StackOverflow中文版his question to explain with more interesting example?
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
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.
精彩评论