user319824
user319824

Reputation:

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?

Upvotes: 1

Views: 241

Answers (2)

Patrick Schlüter
Patrick Schlüter

Reputation: 11841

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.

Upvotes: 1

Mark Rushakoff
Mark Rushakoff

Reputation: 258188

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

Upvotes: 10

Related Questions