for循环中的++i和i++有区别吗?这仅仅是语法问题吗?


当前回答

是的,有。区别在于返回值。"++i"的返回值将是加i之后的值。"i++"的返回值将是加i之前的值。这意味着代码看起来像下面这样:

int a = 0;
int b = ++a; // a is incremented and the result after incrementing is saved to b.
int c = a++; // a is incremented again and the result before incremening is saved to c.

因此,a等于2,b和c都等于1。

我可以像这样重写代码:

int a = 0; 

// ++a;
a = a + 1; // incrementing first.
b = a; // setting second. 

// a++;
c = a; // setting first. 
a = a + 1; // incrementing second. 

其他回答

在这两种情况下,'i'将加1。

但是当你在表达式中使用它时,就有区别了,例如:

int i = 1;
int a = ++i;
// i is incremented by one and then assigned to a.
// Both i and a are now 2.
int b = i++;
// i is assigned to b and then incremented by one.
// b is now 2, and i is now 3

对于用户定义类型的i,这些操作符可以(但不应该)在循环索引上下文中具有有意义的不同语义,这可能(但不应该)影响所描述的循环的行为。

此外,在c++中,使用预增量形式(++i)通常是最安全的,因为它更容易优化。(斯科特·朗廷(Scott Langham)先我一步找到了这个花边新闻。诅咒你,斯科特)

一个(++i)是前增量,一个(i++)是后增量。区别在于表达式立即返回什么值。

// Psuedocode
int i = 0;
print i++; // Prints 0
print i; // Prints 1
int j = 0;
print ++j; // Prints 1
print j; // Prints 1

编辑:哎呀,完全忽略了循环方面的事情。在for循环中,当它是'step'部分(for(…;…。)),但它也可以在其他情况下发挥作用。

在javascript中由于以下原因i++可能更好使用:

var i=1;
alert(i++); // before, 1. current, 1. after, 2.
alert(i); // before, 2. current, 2. after, 2.
alert(++i); // before, 2. current, 3 after, 3.

虽然数组(我认为所有)和其他一些函数和调用使用0作为起点,但当使用++ I时,必须将I设置为-1以使循环与数组一起工作。

当使用i++时,下面的值将使用增加的值。你可以说i++是人类计数的方式,因为你可以从0开始。

在c#中,在for循环中使用没有区别。

for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

输出和

for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }

正如其他人指出的那样,在一般情况下i++和++i有一个微妙但显著的区别:

int i = 0;
Console.WriteLine(i++);   // Prints 0
int j = 0;
Console.WriteLine(++j);   // Prints 1

i++读取I的值,然后增加它。

++i增加i的值,然后读取它。