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


当前回答

我+ +;+ +我;两者都是相似的,因为它们不在表达式中使用。

class A {

     public static void main (String []args) {

     int j = 0 ;
     int k = 0 ;
     ++j;
     k++;
    System.out.println(k+" "+j);

}}

prints out :  1 1

其他回答

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

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

在这两种情况下,'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

对于循环可能会有不同。这是后增量/前增量的实际应用。

        int i = 0;
        while(i++ <= 10) {
            Console.Write(i);
        }
        Console.Write(System.Environment.NewLine);

        i = 0;
        while(++i <= 10) {
            Console.Write(i);
        }
        Console.ReadLine();

虽然第一个数到11,循环11次,但第二个不是。

这通常用于简单的while(x——> 0);- -循环迭代数组中的所有元素(这里不包括foreach-construct)。

如果在循环中不使用增量之后的值,则没有区别。

for (int i = 0; i < 4; ++i){
cout<<i;       
}
for (int i = 0; i < 4; i++){
cout<<i;       
}

这两个循环都输出0123。

但是当你在循环中使用自增/自减后的值时,区别就来了:

预增量循环:

for (int i = 0,k=0; i < 4; k=++i){
cout<<i<<" ";       
cout<<k<<" "; 
}

输出: 0 0 1 2 - 2 3个3

增量后循环:

for (int i = 0, k=0; i < 4; k=i++){
cout<<i<<" ";       
cout<<k<<" "; 
}

输出: 0 0 1 0 2 1 3 - 2

我希望通过比较输出可以清楚地看出差异。这里需要注意的是,递增/递减总是在for循环的末尾执行,因此结果可以解释。

a++被称为后缀。

a加1,返回原来的值。

++a被称为前缀。

对a加1,返回新值。

C#:

string[] items = {"a","b","c","d"};
int i = 0;
foreach (string item in items)
{
    Console.WriteLine(++i);
}
Console.WriteLine("");

i = 0;
foreach (string item in items)
{
    Console.WriteLine(i++);
}

输出:

1
2
3
4

0
1
2
3

Foreach和while循环取决于您使用的增量类型。对于下面这样的for循环,它没有什么区别,因为你没有使用i的返回值:

for (int i = 0; i < 5; i++) { Console.Write(i);}
Console.WriteLine("");
for (int i = 0; i < 5; ++i) { Console.Write(i); }

0, 1, 2, 3, 4 0, 1, 2, 3, 4

如果使用所计算的值,则增量类型变得显著:

int n = 0;
for (int i = 0; n < 5; n = i++) { }