#include <stdio.h>
int main()
{
int a = 10;
if (a == a--)
printf("TRUE 1\t");
a = 10;
if (a == --a)
printf("TRUE 2\t");
}
Why is the second if statement true?
Output is: TRUE 1 TRUE 2
Is this happening due to Undefined behavior because I am comparing same variable with its decremented value?
Correct, the condition evaluates to true
because you see undefined behavior: if a variable with an operator that has side effects is used in an expression, it is illegal to use the same variable again in an expression that has no sequence points (==
does not have sequence points).
This is because the compiler is free to apply the side effect of --
at any time that it wishes, as long as the value that is used when evaluating the expression is correct (i.e. the value before the decrement for postfix notation, or the value after the decrement for the prefix notation).
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