Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'if((x) || (y=z))' work?

Tags:

c

I don't quite understand how the if statement in this case works. It evaluates the x != 0 statement and when that is not true anymore, it assigns z to y and then breaks the if statement?

int main()
{
    int x, y, z, i;
    x = 3;
    y = 2;
    z = 3;

    for (i = 0; i < 10; i++) {
        if ((x) || (y = z)) {
            x--;
            z--;
        } else {
            break;
        }
    }

    printf("%d %d %d", x, y, z);
}
like image 392
Mike B. Avatar asked Mar 08 '17 19:03

Mike B.


1 Answers

Let's decompose that into smaller bits.

  1. if (x) is the same as if (x != 0). If x != 0, then you know the condition is true, so you don't do the other portion of the if.

  2. If part 1. was false, then y = z assigns z into y and returns the final value of y.

  3. From point 2., we can understand that if (y = z) is equivalent to y = z; if (y != 0)


Thus, from points 1. and 3., we can understand that :

if ((x) || (y = z)) {
    doSomething();
}
else {
    doSomethingElse();
}

Is the same as :

if (x != 0) {
    doSomething();
}
else {
    y = z;
    if (y != 0) {
        doSomething();
    }
    else {
        doSomethingElse();
    }
}

It's true it's not particularly readable code though.

like image 154
AnthonyD973 Avatar answered Oct 21 '22 09:10

AnthonyD973