C# Post Increment [duplicate]
Asked Answered
E

3

11

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?

Electrum answered 25/12, 2016 at 10:57 Comment(0)
G
10

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.

Grommet answered 25/12, 2016 at 11:5 Comment(0)
C
1

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.

Castorina answered 25/12, 2016 at 11:8 Comment(2)
In the second case bool b = i == i++; i.e. 0 == 0 which is true and then increment happens. like first the value is compared and then i is incremented But in first case it is happening other way round like bool b = i++ == i; i.e. 0 == 1 it first read 0 then increment i and then compare it by that time i is incremented to 1 that is why he is getting false.Pillory
That is correct.The second snippet of code is self-understandable if you understand the concept behind the first part.It's the same in most programming languages.It's a fundamental basic concept.Castorina
I
1

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
Ixion answered 25/12, 2016 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.