C# Post Increment

531 views Asked by At

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?

3

There are 3 answers

0
AudioBubble On BEST ANSWER

Suppose i has the value 0 initially, as it does in your examples.

i++ == i reads i (0), increments i, reads i again (1), and compares the two values: 0 == 1.

i == i++ reads i (0), reads i again (0), increments i, and compares the two values: 0 == 0.

The increment happens immediately after reading the old value.

2
Taufiq Rahman On

Answering to your first snippet of code:

Here, bool b = i++ == i;is 0 == 1and this is because as you know i++ is a post increment so i remains 0 at i++ but after that part is finished executing and it is being compared to the right hand side which is i , by this time the value has change to 1 due to that previous post increment. This is why you are getting False when doing : bool b = i++ == i;.

Like @hvd said: The increment happens immediately after reading the old value.

0
Abdul Mateen Mohammed On

The order of evaluation of the postfix and the equality operator is from left to right, so the code behaves as explained in the code comments.

int i = 0;
bool b = i++ == i;
// 1.) i++ returns old value i.e. 0
// 2.) but after that it increments and becomes 1
// 3.) hence, bool b = 0 == 1; --> evaluates to false
Console.WriteLine(b); // prints false

int i = 0;
bool b = i == i++;
// 1.) i returns old value i.e. 0
// 2.) i++ returns old value i.e. 0, as this is the end of the statement after that it would increment
// 3.) hence, bool b = 0 == 0; --> evaluates to true
Console.WriteLine(b); // prints true