Break; continue; goto; return application in the loop, continuegoto

Source: Internet
Author: User

Break; continue; goto; return application in the loop, continuegoto

1. break indicates that the program jumps out of the loop and points to the first statement after the loop body;

Int I = 1;

While (I <= 10)

{

If (I = 6)

Break;

Console. writeline ("{0}", I ++ );

}

Console. readkey ();

The variable I is increased to 6 and then jumps out of the loop. The program then executes console. readkey ();

 

2. continue only indicates that the current loop exists, rather than the entire loop body.

Int I;

For (I = 1; I <= 10; I ++)

{

If (I % 2 = 0)

Continue;

Console. writeline (I );

}

When I is an even number, the current loop exists, but the loop continues until I> 10. Therefore, the running result is, 9.

 

3. goto can jump out of the loop body to the label statement. It is not recommended for beginners to use goto.

Int I = 1;

While (I <= 10)
{
If (I = 6)
{
Goto exitpoint;
}
Console. WriteLine ("{0}", I ++ );
}
Console. WriteLine ("this code will never be reached! "); // This statement cannot be executed
Exitpoint:
Console. WriteLine ("the loop use goto! ");
Console. WriteLine ("goto can contain several sentences! ");
Console. ReadKey ();

When I = 6, the loop body jumps out and executes the goto statement, but the program behind the loop body cannot be executed.

 

4. return exits the entire method containing the loop body,

Static void Main (string [] args)
{
Printout ();
Console. WriteLine ("out of printout method! ");
Console. ReadKey ();
}
Static void printout ()
{
Int I = 1;
While (I <= 10)
{
If (I = 6)
{
Return;
}
Console. WriteLine ("{0}", I ++ );
}
Console. WriteLine ("this code will never be reached! "); // Execution failed
}

When I = 6, the printout () method is directly displayed.

 

Related Article

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.