在C语言中,使用++i和i++之间的区别是什么,在for循环的增量块中应该使用哪个?
当前回答
++i(前缀操作):递增,然后赋值 (例如):int I = 5, int b = ++ I 在这种情况下,先将6赋值给b,然后递增到7,依此类推。
i++(后缀操作):赋值,然后递增 (例如):int I = 5, int b = i++ 在这种情况下,5首先被赋值给b,然后增加到6,依此类推。
在for循环的情况下:i++主要用于,因为通常我们在for循环中递增之前使用i的起始值。但是根据您的程序逻辑,它可能会有所不同。
其他回答
你可以把它的内部转换看作是多条语句:
// 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++是后增量,因为它在操作结束后将I的值加1。
让我们看看下面的例子:
int i = 1, j;
j = i++;
这里j = 1,但i = 2。在这里,i的值将首先赋给j,然后i将增加。
++i
++i是预增量,因为它在操作之前将i的值加1。 它表示j = i;将在i++之后执行。
让我们看看下面的例子:
int i = 1, j;
j = ++i;
这里j = 2但是i = 2。这里i的值将在i增加i之后赋给j。 类似地,++i将在j=i;之前执行。
对于你的问题,在For循环的增量块中应该使用哪个?答案是,你可以用任何一个…没关系。它将执行相同次数的for循环。
for(i=0; i<5; i++)
printf("%d ", i);
And
for(i=0; i<5; ++i)
printf("%d ", i);
两个循环将产生相同的输出。也就是0 1 2 3 4。
重要的是你在哪里使用它。
for(i = 0; i<5;)
printf("%d ", ++i);
在这种情况下,输出将是1 2 3 4 5。
预填充是指在同一行上的增量。后增量是指行执行后的增量。
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).
}
简单地说,两者之间的区别在于步骤,请看下图。
例子:
int i = 1;
int j = i++;
j的结果是1
int i = 1;
int j = ++i;
j的结果是2
注意:在这两种情况下i的值都是2