int a = 5;
if(a==a++){
printf("true 1");
}
if(a==++a){
printf("true 2");
}
When I run this code, it prints "true 2". I do not understand how. Please help. Also, how is logical equivalence computed in precedence with increment operators?
int a = 5;
if(a==a++){
printf("true 1");
}
if(a==++a){
printf("true 2");
}
When I run this code, it prints "true 2". I do not understand how. Please help. Also, how is logical equivalence computed in precedence with increment operators?
The order of evaluation in a==++a
is not defined by the standard. Thus the ++
can be performed before the comparison or after comparison. With another compiler you can get different results. This is called 'UB', or 'Undefined Behavior'.
This code will give Undefined Behavior in many ways. But if you initialize a
, the difference is that ++a
will return the incremented value, while a++
will return the new value.
Also, in for
loops, you should use ++a
and you will not go wrong.
Let's evaluate your problem.
In the first case, when you compare a
with the incremented value of a
(as a++
return the incremented value), so it is false. Example: a
has 5, and the incremented value is 6. So, as they do not match, it will be a false.
In the second case, when you compare a
with the old value of a
(as ++a
returns the original value), you get true. Example: a
has 5 and when you increment it using ++a
, you get the old/original value, which is also 5. Thus, you get a true.