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 break
s 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);
}
Let's decompose that into smaller bits.
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
.
If part 1. was false
, then y = z
assigns z
into y
and returns the final value of y
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With