No escape from the pit--not break out in time for the For loop

Source: Internet
Author: User

The word "break" is not unfamiliar, the most common is in the switch statement.

If you forget to break after the case of switch, the corresponding statement to the next case is executed sequentially.

I said this is only for C + +, C sharp If you forget the break, the compiler will error.

Think about it as if you had not used the break in other places. caused himself to fall into a big hole again.

For example, use a For loop to find the your_find corresponding index in the array of elements you want:

intindex0;for(int i=; i<1000; i++){    if(array[i] == your_find)    {        index = i;    }}

In this case, the Code of Appeal will complete the entire for loop.
In order to improve efficiency, if we can determine that there is only one index in array arrays that corresponds to Your_find, you can modify the code as follows:

intindex0;for(int i=; i<1000; i++){    if(array[i] == your_find)    {        index = i;        break;    }}

Well, when the statement in the if is true, jump out of the for loop.

The following extension, then for the double loop, the execution of a break, which is to jump out of which loop?
The simplest way to write a code test:

for(int j=0;j<=20;j++){   for(int i=0;i<=10;i++)   {        if(i==5break;   }   if(j==20cout<<" ‘break‘ break from the nearest loop"<<endl;}cout<<j<<endl;cout<<i<<endl;

The output of the above code is:
Break ' break from the nearest loop '
21st
5

So you can be sure that break is jumping out of the nearest layer of the loop.

No holes escaped--no break out for the for loop in time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.