continue与break的理解

经过网上的一些例子,一些小总结:
ide

break用法:it

#include <stdio.h>
int main(void)
{
   int ch;
   
   for(ch = 0; ch < 6; ch++)
   {
       if(ch == 3)
       {
           printf("break\n");
           break;
           printf("I love you\n");
       }
       printf("now ch = %d\n",ch);
   }
   printf("test over!!\n");
   return 0;
}

总结:若是遇到break,程序就会终止并推出,因此后面的‘我爱你’也不会打印,由于now ch = %d也是属于循环里的,因此也不会打印出now ch = 3.io


二,嵌套循环(break)class

#include <stdio.h>
int main(void)
{
    int ch, n;
    
    for(ch = 0; ch < 6; ch++)
    {
        printf("start...\n");
        for(n = 0; n < 6;n++)
        {
            if(n == 3)
            {
                printf("break\n");
                break;
                printf("helloworld\n");
            }
            printf("now n = %d\n",n);
        }
        if(ch == 3)
        {
            printf("break\n");
            break;
            printf("haha\n");
        }
        printf("now ch = %d\n",ch);
    }
    printf("test over\n");
    return 0;
}

 总结:break只会影响到最靠近他的循环,最外层的循环不会干预,每次里边的循环结束后,再跳到外层循环。对于'helloworld','haha'在程序中根本没其做用,也不会打印'now ch = 3' 和'now n = 3'.
test


continue用法:循环

#include <stdio.h>
int main(void)
{
    int ch;
    
    for(ch = 0;ch < 6;ch++)
    {
        printf("start...\n");
        if(ch == 3)
        {
            printf("continue\n");
            continue;
            printf("helloworld\n");
        }
        printf("now ch = %d\n",ch);
    }
    printf("test over\n");
    return 0;
}

  总结:continue没有break那样无情,只是终止当前这一步的循环,只要是包括在这个循环里的,后面的都终止,(break其实也是这样).而后跳过这一步继续循环.程序


循环嵌套(continue):总结

#include <stdio.h>
int main(void)
{
    int ch, n;
    
    for(ch = 0;ch <6;ch++)
    {
        printf("start...\n");
        for(n = 0;n <6;n++)
        {
            if(n == 3)
            {
                printf("continue\n");
                continue;
                printf("helloworld\n");
            }
            printf("now n = %d\n",n);
        }
        if(ch == 3)
        {
            printf("continue\n");
            continue;
            printf("haha\n");
        }
        printf("now ch = %d\n",ch);
     }
     printf("test over!!\n");
     return 0;
 }
 
总结:他也是只会影响到最里边的那一层。其余同上!
相关文章
相关标签/搜索