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


当前回答

++i:是增量前,另一个是增量后。

i++:获取元素,然后对其进行递增。 ++i:增加i,然后返回元素。

例子:

int i = 0;
printf("i: %d\n", i);
printf("i++: %d\n", i++);
printf("++i: %d\n", ++i);

输出:

i: 0
i++: 0
++i: 2

其他回答

请不要担心哪个“效率”(真的是速度)更快。现在我们有编译器来处理这些事情。使用任何一个有意义的,在此基础上更清楚地表明你的意图。

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

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

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

这种差异可以通过下面这段简单的c++代码来理解:

int i, j, k, l;
i = 1; //initialize int i with 1
j = i+1; //add 1 with i and set that as the value of j. i is still 1
k = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1
l = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.
cout << i << ' ' << j << ' ' << k << ' '<< l << endl;
return 0;

简单地说,两者之间的区别在于步骤,请看下图。

例子:

int i = 1;
int j = i++;

j的结果是1

int i = 1;
int j = ++i;

j的结果是2

注意:在这两种情况下i的值都是2

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

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).
}