C: for循环有两个变量和循环移位
C: for loop with two variables and circular shift
我无法弄清楚下面的 for
循环是如何工作的。
#include <stdio.h>
int main()
{
int i, j, n=4;
for (i = 0, j = n-1; i < n; j = i++)
printf("\ni: %d, j:%d", i, j);
return 0;
}
产生:
i: 0, j:3
i: 1, j:0
i: 2, j:1
i: 3, j:2
增量规则j = i++
让我很困惑。我没有得到 j
的循环移位行为。另外,i
没有递增规则,它加1。有人能解释一下吗?
以这种形式编写的for
循环
for(init; cond; incr) { instruction bloc }
可以改写成那种形式:
init;
while(cond)
{
instruction bloc;
incr;
}
所以你可以用另一种方式编写你的循环:
int i, j, n=4;
// first parameter of for loop
i = 0;
j = n-1;
// second parameter of for loop : while the condition is true, stay in instruction bloc
while( i < n) {
// instruction bloc
printf("\ni: %d, j:%d", i, j);
// third parameter: executed after instruction bloc
j = i++
}
由此你可以理解i
和j
是如何增加的:
j = i++;
可以重写:
j = i;
i = i + 1;
我无法弄清楚下面的 for
循环是如何工作的。
#include <stdio.h>
int main()
{
int i, j, n=4;
for (i = 0, j = n-1; i < n; j = i++)
printf("\ni: %d, j:%d", i, j);
return 0;
}
产生:
i: 0, j:3
i: 1, j:0
i: 2, j:1
i: 3, j:2
增量规则j = i++
让我很困惑。我没有得到 j
的循环移位行为。另外,i
没有递增规则,它加1。有人能解释一下吗?
以这种形式编写的for
循环
for(init; cond; incr) { instruction bloc }
可以改写成那种形式:
init;
while(cond)
{
instruction bloc;
incr;
}
所以你可以用另一种方式编写你的循环:
int i, j, n=4;
// first parameter of for loop
i = 0;
j = n-1;
// second parameter of for loop : while the condition is true, stay in instruction bloc
while( i < n) {
// instruction bloc
printf("\ni: %d, j:%d", i, j);
// third parameter: executed after instruction bloc
j = i++
}
由此你可以理解i
和j
是如何增加的:
j = i++;
可以重写:
j = i;
i = i + 1;