请帮我理解为什么在第一个案例中变量a
没有增加,而在第二个案例中却增加了。
案例1:
int a = 10;
a = a++;
Console.WriteLine(a); //prints 10
案例2:
int a = 10;
int c = a++;
Console.WriteLine(a); //prints 11
我已经查看了其他类似的问题,但没有找到具体的答案。
更新1:我的程序流程如下:
情况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
案例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
更新2: 感谢所有的回答,我认为我已经理解了,如果我有错,请纠正我。
情况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
案例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++;
- chouaibunsafe
部分外,除此之外没有“未定义行为”(不在可管理、安全、可编译的代码中)。 - Jcl