Could you please help me understand why variable a
is not incremented in the first case but it is in the second case?
Case 1:
int a = 10;
a = a++;
Console.WriteLine(a); //prints 10
Case 2:
int a = 10;
int c = a++;
Console.WriteLine(a); //prints 11
I've gone through other similar questions but couldn't find any specifics.
UPDATE 1: How I think the program flows
Case 1:
1. 'a' is assigned 10
2. 'a' is assigned 10 before increment happens
3. 'a' is incremented by 1 (Why doesn't this step affect the final value of 'a'?)
4. 'a' is printed --> 10
Case 2:
1. 'a' is assigned 10
2. 'c' is assigned 10 before 'a' is incremented
3. 'a' is incremented by 1 (Why does the increment of 'a' work here?)
4. 'a' is printed --> 11
UPDATE 2: Thanks to all the answers, i think i've understood it, please correct me if i'm wrong.
Case 1:
1. `a` is assigned 10
2. Compiler evaluates `a++`, stores old value 10 and new value 11 as well. Since it's a post increment operation, assigns the old value to `a`. What i thought was, compiler would assign the old value 10 first and evaluate the `++` operation later. This is where i was wrong, compiler evaluates the RHS beforehand and assigns the value based on the operator.
4. 'a' is printed --> 10
Case 2:
1. `a` is assigned 10
2. Compiler evaluates `a++`, stores old value 10 and new value 11 as well. Since it's a post increment operation, assigns the old value to `c` but value of `a` is preserved with `11`.
4. 'a' is printed --> 11
a=a++;
– CantileverUndefined Behavior
is close to the termdon't care state
in digital, it means it compiles, it is correct, but can't expect the result of it – Cantileverunsafe
parts, there's no such thing as "undefined behaviour" (not in managed, safe, compilable code) in c# – Yettie