一般说来,程序进入循环体后在下次循环判断之前执行循环体里的所有语句,break和continue语句可以终止循环或忽略某些循环。
break: 此语句导致程序终止包含它的循环,并进行程序的下一阶段(整个循环后面的语句),即,不是跳到下一个循环周期而是退出循环。如果break语句包含在嵌套循环里,它只跳出最里面的循环。
#include<stdio.h>
int main()
{
int res=0;
int i=0;
int n=0;
printf("test break and continue\n");
for(i=0;i<6;i++)
{
printf("start...\n");
if(i==3)
{
printf("break \n");
break;
printf("break after\n");
//printf("continue \n");
//continue;
//printf("continue after\n");
}
printf("now i = %d\n",i);
}
printf("test over !!!\n");
return 0;
}
$ gcc -o bc bc.c
$ ./bc
test break and continue
start...
now i = 0
start...
now i = 1
start...
now i = 2
start...
break
test over !!!
$
嵌套循环(break):
#include<stdio.h>
int main()
{
int res=0;
int i=0;
int n=0;
printf("test break and continue\n");
for(i=0;i<6;i++)
{
printf("start...\n");
for(n=0;n<6;n++)
{
if(n==3)
{
printf("break \n");
break;
//printf("continue \n");
//continue;
}
printf("now n= %d\n",n);
}
if(i==3)
{
printf("break \n");
break;
printf("break after\n");
//printf("continue \n");
//continue;
//printf("continue after\n");
}
printf("now i = %d\n",i);
}
printf("test over !!!\n");
return 0;
}
$ gcc -o bc bc.c
$ ./bc
test break and continue
start...
now n= 0
now n= 1
now n= 2
break
now i = 0
start...
now n= 0
now n= 1
now n= 2
break
now i = 1
start...
now n= 0
now n= 1
now n= 2
break
now i = 2
start...
now n= 0
now n= 1
now n= 2
break
break
test over !!!
$
continue:
循环语句里有此语句时,程序运行到此语句时,不在执行循环体里continue后面的语句而是跳到下一个循环入口处执行下一个循环。如果continue语句包含在嵌套循环语句里,它只影响包含它的最里层的循环。
#include<stdio.h>
int main()
{
int res=0;
int i=0;
int n=0;
printf("test break and continue\n");
for(i=0;i<6;i++)
{
printf("start...\n");
if(i==3)
{
//printf("break \n");
//break;
//printf("break after\n");
printf("continue \n");
continue;
printf("continue after\n");
}
printf("now i = %d\n",i);
}
printf("test over !!!\n");
return 0;
}
$ gcc -o bc bc.c
$ ./bc
test break and continue
start...
now i = 0
start...
now i = 1
start...
now i = 2
start...
continue
start...
now i = 4
start...
now i = 5
test over !!!
$
嵌套循环(continue):
#include<stdio.h>
int main()
{
int res=0;
int i=0;
int n=0;
printf("test break and continue\n");
for(i=0;i<6;i++)
{
printf("start...\n");
for(n=0;n<6;n++)
{
if(n==3)
{
//printf("break \n");
//break;
printf("continue \n");
continue;
}
printf("now n= %d\n",n);
}
if(i==3)
{
//printf("break \n");
//break;
//printf("break after\n");
printf("continue \n");
continue;
printf("continue after\n");
}
printf("now i = %d\n",i);
}
printf("test over !!!\n");
return 0;
}
$ gcc -o bc bc.c
$ ./bc
test break and continue
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 0
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 1
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 2
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
continue
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 4
start...
now n= 0
now n= 1
now n= 2
continue
now n= 4
now n= 5
now i = 5
test over !!!
$