在C语言中,使用++i和i++之间的区别是什么,在for循环的增量块中应该使用哪个?
当前回答
:不久
++i和i++的工作原理是一样的,如果你不在函数中写它们的话。如果你使用function(i++)或function(++i),你可以看到区别。
函数(++i)表示首先将i增加1,然后将i放入具有新值的函数中。
Function (i++)表示在i加1之后将第一个i放入函数中。
int i=4;
printf("%d\n",pow(++i,2));//it prints 25 and i is 5 now
i=4;
printf("%d",pow(i++,2));//it prints 16 i is 5 now
其他回答
:不久
++i和i++的工作原理是一样的,如果你不在函数中写它们的话。如果你使用function(i++)或function(++i),你可以看到区别。
函数(++i)表示首先将i增加1,然后将i放入具有新值的函数中。
Function (i++)表示在i加1之后将第一个i放入函数中。
int i=4;
printf("%d\n",pow(++i,2));//it prints 25 and i is 5 now
i=4;
printf("%d",pow(i++,2));//it prints 16 i is 5 now
这种差异可以通过下面这段简单的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;
你可以把它的内部转换看作是多条语句:
// case 1
i++;
/* you can think as,
* i;
* i= i+1;
*/
// case 2
++i;
/* you can think as,
* i = i+i;
* i;
*/
A =i++表示A包含当前i的值。
A =++i表示A包含i的增量值。
++i可以比i++稍微快一点的原因是,i++可以在i的值被递增之前要求它的本地副本,而++i从不这样做。在某些情况下,一些编译器会尽可能地优化它……但这并不总是可能的,并不是所有编译器都这样做。
我尽量不太依赖编译器优化,所以我会遵循Ryan Fox的建议:当我可以使用两者时,我会使用++ I。