怎样才能知道循环是否提前结束了
循环通常依赖于一个或多个变量,你可以在循环外检查这些变量,以确保循环被正确执行。请看下例:
int x
char * cp[REQUESTED_BLOCKS]
/ * Attempt (in vain, I must add... )to
allocate 512 10KB blocks in memory. * /
for (x = 0; x<REQUESTED_ BLOCKS ; x++ )
{
cpi[x]= (char * ) malloc (10000,1)
if (cp[x]= = (char * ) NULL)
break
}
/ * If x is less than REQUESTED-BLOCKS,
the loop has ended prematurely. * /
if (x<REQUESTED_BLOCKS)
printf ("Bummer ! My loop ended prematurely ! \n" );
注意:如果上述循环执行成功,它一定会循环512次。紧接着循环的if语句用来测试循环次数,从而判断循环是否提前结束。如果变量x的值小于512,就说明循环出错了。
int x
char * cp[REQUESTED_BLOCKS]
/ * Attempt (in vain, I must add... )to
allocate 512 10KB blocks in memory. * /
for (x = 0; x<REQUESTED_ BLOCKS ; x++ )
{
cpi[x]= (char * ) malloc (10000,1)
if (cp[x]= = (char * ) NULL)
break
}
/ * If x is less than REQUESTED-BLOCKS,
the loop has ended prematurely. * /
if (x<REQUESTED_BLOCKS)
printf ("Bummer ! My loop ended prematurely ! \n" );
注意:如果上述循环执行成功,它一定会循环512次。紧接着循环的if语句用来测试循环次数,从而判断循环是否提前结束。如果变量x的值小于512,就说明循环出错了。