arr[0]++ 之间的区别和 ++arr[0]
在 C# 中,代码(全部在一个语句中,而不是较大语句的一部分)arr[0]++;
和 ++arr[0];
之间有区别吗? code>
我完全理解,在 C / C++ / Objective-C 中,这不会做同样的事情,第一种情况会获取 arr 的第 0 个索引处的值并将该值增加 1,而第二种情况,增加 arr 的指针值,并且对它的第 0 个位置不执行任何操作(与 arr[1]; arr++; 相同)。
感谢某事,他提醒我这是相同的在 C# 和 C / C++ / Obj-C 中。
但是,这两个语句在 C# 中有区别吗?
In C#, is there a difference between the code (all in one statement, not part of a larger one) arr[0]++;
and ++arr[0];
I fully understand, that in C / C++ / Objective-C, that this would not do the same thing, first case would get the value at arr's 0th index and increment that value by one, while the second one, increases the pointer value of arr, and does nothing to it's 0th position (same as arr[1]; arr++;
).
Thanks to sth, he has reminded me that this is the same in C# and C / C++ / Obj-C.
However, is there a difference between the two statements in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
arr[0]++
返回arr
第一个元素的值,然后递增它。++arr[0]
递增arr
第一个元素的值,然后返回它。仅当您将其用作较长指令的一部分时,差异才有意义。例如:
不等于:
arr[0]++
returns the value of the first element ofarr
, then increments it.++arr[0]
increments the value of the first element ofarr
, then returns itThe difference only matters if you're using this as part of a longer instruction. For instance :
Is not the same as:
如果它是单个语句,则没有区别。
If it is a single statement there is no difference.
++x 递增然后返回,而 x++ 返回 x 的值然后递增!
但如果没有人接收到这个值,那就都一样了。
++x increments and then returns while x++ returns the value of x and then increments !
But if there is no one to receive the value, its all the same.
如果该语句本身存在,优化编译器应该生成相同的代码,但是当您使用要内联修改的值时,后增量可能需要制作副本(以便您可以使用旧值),这可以如果数组是具有昂贵的复制构造函数的类型,则成本昂贵。
An optimizing compiler should generate the same code if that statement exists by itself, but when you're using the value you're modifying inline, post-increment can require making a copy (so you can work with the old value), which can be expensive if the array is of a type that has an expensive copy constructor.