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


当前回答

关于++i和i++,不仅仅是循环和性能差异。++i返回一个l值,i++返回一个r值。基于此,可以对(++i)执行许多操作,但不能对(i++)执行许多操作。

1- It is illegal to take the address of post increment result. Compiler won't even allow you.
2- Only constant references to post increment can exist, i.e., of the form const T&.
3- You cannot apply another post increment or decrement to the result of i++, i.e., there is no such thing as I++++. This would be parsed as ( i ++ ) ++ which is illegal.
4- When overloading pre-/post-increment and decrement operators, programmers are encouraged to define post- increment/decrement operators like:

T& operator ++ ( )
{
   // logical increment
   return *this;
}

const T operator ++ ( int )
{
    T temp( *this );
    ++*this;
    return temp;
}

其他回答

关于++i和i++,不仅仅是循环和性能差异。++i返回一个l值,i++返回一个r值。基于此,可以对(++i)执行许多操作,但不能对(i++)执行许多操作。

1- It is illegal to take the address of post increment result. Compiler won't even allow you.
2- Only constant references to post increment can exist, i.e., of the form const T&.
3- You cannot apply another post increment or decrement to the result of i++, i.e., there is no such thing as I++++. This would be parsed as ( i ++ ) ++ which is illegal.
4- When overloading pre-/post-increment and decrement operators, programmers are encouraged to define post- increment/decrement operators like:

T& operator ++ ( )
{
   // logical increment
   return *this;
}

const T operator ++ ( int )
{
    T temp( *this );
    ++*this;
    return temp;
}

一个(++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(…;…。)),但它也可以在其他情况下发挥作用。

在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的值,然后读取它。

我不知道其他语言,但在java++中,I是一个前缀增量,这意味着:将I增加1,然后在I所在的表达式中使用I的新值,i++是一个后缀增量,这意味着:在表达式中使用I的当前值,然后将其增加1。 例子:

public static void main(String [] args){

    int a = 3;
    int b = 5;
    System.out.println(++a);
    System.out.println(b++);
    System.out.println(b);

} 输出为:

4 5 6

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

        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)。