c#中的后增量问题? [英] Problem with post increment in c#?

查看:76
本文介绍了c#中的后增量问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int x = 20;
x = x++;
Console.WriteLine(x); 





在上面的陈述中x = x ++;



为什么x值没有增加。



我这里有点混乱。请解释一下。



In the above statement x=x++;

why x value is not increment.

I have a little bit confusion here. Please explain about this.

推荐答案

这很清楚。



我会问你:结果如何你有没有预料到为什么?您是否期望21,如 y = x ++ ?没门!编译器不应该,也不应该对开发人员的意图做出任何假设,它应该遵循简单严格的原则。如果你做了一些没有实际意义的奇怪的东西,就像在这种情况下,逻辑和表观结果也可能看起来很奇怪。



编译器需要估计右边的表达式两次,在++之前和之后,因为这是后增量。分配需要之前的值;和值后是增量的结果。当双方都出现 x 时,堆栈上的附加(临时)插槽将被保留,以使用右侧的表达式进行操作。估计 x ,这是20.然后将20分配给代表变量 x 的第一个槽。它变为20.然后表示右边的表达式的内存位置需要增加1.它变为21.从堆栈帧存在,该值被丢弃。



这是对增量赋值给同一变量的唯一逻辑解释。如果你反汇编这段代码,你可以很容易地看到它是如何工作的。



你应该明白这是病态案例,在实践中完全没有意义。可以通过编写 ++ x x ++ 来执行增量。如果将结果分配给不同的变量,则增量与分配的组合才有意义。



我感谢您对某些病态案例感兴趣。它让我们认为某些操作并不像它们看起来那么简单,并且在使用增量时需要谨慎使用。



-SA
This is pretty clear.

I would ask you: what result did you expected and why? Did you expect 21, as in case of y = x++? No way! Compiler is not supposed and should not make any assumption on the developer's intention, it should follow simple and strict principles. If you do weird thing which makes no practical sense, as in this case, the logical and apparent result may also appear weird.

The compiler needs to estimate expression on right two times, before ++ and after, because this is post-increment. The value "before" is needed for assignment; and value "after" is the result of increment. As x appears in both sides, the addition (temporary) slot on stack is reserved, to manipulate with the expression on right. The x estimated, this is 20. Then 20 is assigned to first slot representing variable x. It becomes 20. Then the memory location representing expression on right needs to be incremented by 1. It becomes 21. On exist from the stack frame, this value is discarded.

This is the only logical interpretation of post-increment with assignment to the same variable. You can easily see how it works if you disassemble this fragment of code.

You should understand that this is the pathological case which makes no sense at all in practice. Increment can be performed by writing ++x or x++. Combination of increment with assignment only makes sense if the result is assigned to a different variable.

I appreciate your interest to some pathological cases. It gives us the idea that some operations are not as trivial as they seem and that caution needs to be used when working with increments.

—SA


U正在使用后增量(x ++),因此只有x的值不会在第一时间递增。

使用预增量(++) x)。



++ x在评估之前递增a。 x ++计算a然后递增它。
U are using the post increment (x++) so only the value of x is not incremented at first time.
Use the pre increment (++x).

++x increments a before it is evaluated. x++ evaluates a and then increments it.


这篇关于c#中的后增量问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆