zoukankan      html  css  js  c++  java
  • break 和 continue

    break 和 continue

     相同点:

     都 用在循环体内,如 switch、for、while、do while的程序块中,用于控制程序循环语句的执行

    不同点:

       break可以离开当前switch、for、while、do while的程序块,并前进至程序块后下一条语句,在switch中主要用来中断下一个case的比较。在for、while与do while中,主要用于中断目前的循环执行。

     break用于强行退出当前循环,结束程序块的执行,不会执行循环中剩余的语句

     continue  会在结束当前循环后,继续执行剩余的循环,并跳回循环程序块的开头继续下一个循环,而不是退出循环体。

    在嵌套循环中,break语句仅退出包含它的最内层循环。而continue语句会将控制传递给包含该语句的循环的下一次迭代。

    例如下列的程序:

            public static void  TestBreak()
            {
                for (int i = 0; i < 10; i++)
                {               
                     if(i==5)
                     {
                        Console.WriteLine(" break at 5");
                         break;
                     }
    
                     Console.WriteLine(" {0}", i);
                }
            }
    

     运行结果:

            public static  void TestContinue()
            {
                for (int i = 0; i < 10; i++)
                {
                    if (i == 5)
                    {
                        Console.WriteLine(" break  at 5, but continue running");
                        continue;
                    }
    
                    Console.WriteLine(" {0}", i);
                }
            }
    

     运行结果:

    从break 和 continue 程序的运行效果,可以很清楚的看到  break 和 continue 的区别所在

  • 相关阅读:
    Median Value
    237. Delete Node in a Linked List
    206. Reverse Linked List
    160. Intersection of Two Linked Lists
    83. Remove Duplicates from Sorted List
    21. Merge Two Sorted Lists
    477. Total Hamming Distance
    421. Maximum XOR of Two Numbers in an Array
    397. Integer Replacement
    318. Maximum Product of Word Lengths
  • 原文地址:https://www.cnblogs.com/wisdo/p/4514934.html
Copyright © 2011-2022 走看看