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


当前回答

++i增加值,然后返回该值。

i++返回值,然后使其递增。

这是一个微妙的区别。

对于For循环,使用++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;

A =i++表示A包含当前i的值。

A =++i表示A包含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,然后返回元素。

例子:

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

输出:

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