在C语言中,使用++i和i++之间的区别是什么,在for循环的增量块中应该使用哪个?


当前回答

++i可以比i++稍微快一点的原因是,i++可以在i的值被递增之前要求它的本地副本,而++i从不这样做。在某些情况下,一些编译器会尽可能地优化它……但这并不总是可能的,并不是所有编译器都这样做。

我尽量不太依赖编译器优化,所以我会遵循Ryan Fox的建议:当我可以使用两者时,我会使用++ I。

其他回答

预填充是指在同一行上的增量。后增量是指行执行后的增量。

int j = 0;
System.out.println(j); // 0
System.out.println(j++); // 0. post-increment. It means after this line executes j increments.

int k = 0;
System.out.println(k); // 0
System.out.println(++k); // 1. pre increment. It means it increments first and then the line executes

当它带有OR和AND操作符时,它变得更有趣。

int m = 0;
if((m == 0 || m++ == 0) && (m++ == 1)) { // False
    // In the OR condition, if the first line is already true
    // then the compiler doesn't check the rest. It is a
    // technique of compiler optimization
    System.out.println("post-increment " + m);
}

int n = 0;
if((n == 0 || n++ == 0) && (++n == 1)) { // True
    System.out.println("pre-increment " + n); // 1
}

在数组中

System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 };
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); // 12

jj = a[1]++; // 12
System.out.println(a[1]); // a[1] = 13

mm = a[1]; // 13
System.out.printf("\n%d %d %d\n", ii, jj, mm); // 12, 12, 13

for (int val: a) {
     System.out.print(" " + val); // 55, 13, 15, 20, 25
}

在c++中,指针变量的后/前增量

#include <iostream>
using namespace std;

int main() {

    int x = 10;
    int* p = &x;

    std::cout << "address = " << p <<"\n"; // Prints the address of x
    std::cout << "address = " << p <<"\n"; // Prints (the address of x) + sizeof(int)
    std::cout << "address = " << &x <<"\n"; // Prints the address of x

    std::cout << "address = " << ++&x << "\n"; // Error. The reference can't reassign, because it is fixed (immutable).
}

你可以把它的内部转换看作是多条语句:

// case 1

i++;

/* you can think as,
 * i;
 * i= i+1;
 */



// case 2

++i;

/* you can think as,
 * i = i+i;
 * i;
 */

i++:在这种情况下,首先赋值,然后进行递增。

++i:在这个场景中,首先完成增量,然后赋值

下面是图像可视化,这里也有一个很好的实用视频,演示了同样的。

i++和++ I

这段小代码可能有助于从不同的角度来看待与已经发布的答案的差异:

int i = 10, j = 10;
  
printf ("i is %i \n", i);
printf ("i++ is %i \n", i++);
printf ("i is %i \n\n", i);
  
printf ("j is %i \n", j);
printf ("++j is %i \n", ++j);
printf ("j is %i \n", j);

结果是:

//Remember that the values are i = 10, and j = 10

i is 10 
i++ is 10     //Assigns (print out), then increments
i is 11 

j is 10 
++j is 11    //Increments, then assigns (print out)
j is 11 

注意之前和之后的情况。

for循环

至于在for循环的增量块中应该使用它们中的哪一个,我认为我们能做的最好的决定是使用一个很好的例子:

int i, j;

for (i = 0; i <= 3; i++)
    printf (" > iteration #%i", i);

printf ("\n");

for (j = 0; j <= 3; ++j)
    printf (" > iteration #%i", j);

结果是:

> iteration #0 > iteration #1 > iteration #2 > iteration #3
> iteration #0 > iteration #1 > iteration #2 > iteration #3 

我不知道你怎么想,但我没有看到它的用法有任何不同,至少在for循环中是这样。

下面的C代码片段说明了前后递增和递减操作符之间的区别:

int  i;
int  j;

增量运算符:

i = 1;
j = ++i;    // i is now 2, j is also 2
j = i++;    // i is now 3, j is 2