int main() {
int a = 1;
int b = 0;
if (a = b || ++a == 2)
printf("T: a=%i, b=%i", a, b);
else
printf("F: a=%i, b=%i", a, b);
return 0;
}
Let’s take a look at this simple code snippet. Result is: T: a=1, b=0
Why? (note a=b uses assignment operand, not comparison)
What I understand here, is that zero is assigned to a, then a is incremented to 1. 1 is not equal to 2. So result should indeed be a=1, b=0. But why is this condition evaluated to true? Neither of (a=b) or (++a == 2) is true … What did I miss?
Here is other short program that prints F as expected:
int main() {
int a = 1;
int b = 0;
if (a = b) printf("T"); else printf("F");
return 0;
}
You have confused yourself with misleading spacing.
is the same as:
This actually has undefined behavior. Although there is a sequence point between the evaluation of
band the evaluation of((++a) == 2), there is no sequence point between the implied assignment toaand the other write toadue to the explicit=assignment.