++ Var和Var ++之间的区别 [英] The difference between ++Var and Var++
问题描述
在编程中,特别是在Java中,有什么区别:
In programming, particularly in Java, what is the difference between:
int var = 0;
var++;
和
int var = 0;
++var;
这会对for循环产生什么影响?
What repercussions would this have on a for loop?
例如
for (int i = 0; i < 10; i++) {}
for (int i = 0; i < 10; ++i) {}
推荐答案
tldr;
虽然 var ++
和 ++ var
增加它们应用的变量, var ++
返回的结果是增量前变量的值,而返回的结果是 ++ var
是应用增量后变量的值。
tldr;
Although both var++
and ++var
increment the variable they are applied to, the result returned by var++
is the value of the variable before incrementing, whereas the result returned by ++var
is the value of the variable after the increment is applied.
当 ++ var
或 var ++
形成一个完整的陈述(如在你的例子)两者之间没有区别。例如以下
When ++var
or var++
form a complete statement (as in your examples) there is no difference between the two. For example the following
int x = 6;
++x;
assert x == 7;
与
int x = 6;
x++;
assert x == 7;
然而,当 ++ var
或 var ++
用作较大语句的一部分,两者可能不等同。例如,以下断言传递
However, when ++var
or var++
are used as part of a larger statement, the two may not be equivalent. For example, the following assertion passes
int x = 6;
assert ++x == 7;
而这一次失败
int x = 6;
assert x++ == 7;
虽然 var ++
和 ++ var
递增它们应用的变量, var ++
返回的结果是递增前变量的值,而 ++ var
返回的结果是应用增量后变量的值。
Although both var++
and ++var
increment the variable they are applied to, the result returned by var++
is the value of the variable before incrementing, whereas the result returned by ++var
is the value of the variable after the increment is applied.
当在中用于
循环时,两者之间没有区别,因为变量的增量不构成较大语句的一部分。它可能不会以这种方式出现,因为源文件的同一行上还有其他代码。但是如果你仔细观察,你会发现在增量之前有一个;
,之后没有任何内容,所以增量运算符不构成一个更大的语句的一部分。
When used in a for
loop, there is no difference between the two because the incrementation of the variable does not form part of a larger statement. It may not appear this way, because there is other code on the same line of the source file. But if you look closely, you'll see there is a ;
immediately before the increment and nothing afterwards, so the increment operator does not form part of a larger statement.
这篇关于++ Var和Var ++之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!