While I am testing post increment operator in a simple console application, I realized that I did not understand full concept. It seems weird to me:
int i = 0;
bool b = i++ == i;
Console.WriteLine(b);
The output has been false. I have expected that it would be true. AFAIK, at line 2, because of the post increment, compiler does comparison and assigned b to true, after i incremented by one. But obviously I am wrong. After that I modify the code like that:
int i = 0;
bool b = i == i++;
Console.WriteLine(b);
This time output has been true. What did change from first sample?
Suppose
i
has the value0
initially, as it does in your examples.i++ == i
readsi
(0
), incrementsi
, readsi
again (1
), and compares the two values:0 == 1
.i == i++
readsi
(0
), readsi
again (0
), incrementsi
, and compares the two values:0 == 0
.The increment happens immediately after reading the old value.