Break indicates that the current loop is exited. return indicates the end of the entire function, and its subsequent statements are not executed.
For example
1. Use break in the switch
Public void FunTest
{
Int a = 1;
Switch ()
{
Case 1:
// Several cases can be written together. For example, case 2 can be added here:
Console. WriteLine ("this is 1 ");
Break;
Default:
Break;
}
Console. WriteLine ("this is end ");
}
The switch statement must have a break. Otherwise, an error is reported. The output result is This is 1 this is end;
2. Use return in the switch statement
Public void FunTest
{
Int a = 1;
Switch ()
{
Case 1:
Console. WriteLine ("this is 1 ");
Return;
Default:
Break;
}
Console. WriteLine ("this is end"); // this statement will not be executed
}
The entire function ends when return is executed, so the second output statement is not executed. the printed result is this is 1. here, the function does not return values, so return is used. If a return value exists, add a value after return.
3. Use break in the for statement.
Public void FunTest ()
{
For (int I = 0; I <4; I ++)
{
Console. WriteLine (I );
If (I = 1)
Break;
}
Console. WriteLine ("end ");
}
The print result is 0 1 end. When I is 1, break exits the entire for loop, SO 2 3 is not printed.
4. Use return in the for statement
Public int FunTest ()
{
For (int I = 0; I <4; I ++)
{
Console. WriteLine (I );
If (I = 1)
Return 1;
}
// None of the subsequent statements are executed
Console. WriteLine ("end ");
Return 0;
}
The output here is 01, and the end is not printed. the return value of the function is 1.
5. Use return for finally Functions
Although most of the time the return function is executed, there is a special case where the finally code will still be executed.
Public int FunTest ()
{
Try
{
Console. WriteLine ("step one ");
Return 1;
Console. WriteLine ("step two"); // not executed here
}
Finally
{
Console. WriteLine ("step three"); // This will be executed
}
Return 2; // not executed here
}
The printed result here is step one, And step three. The return value of the function is 1. In addition, the finally block cannot contain return.
6. continue indicates that the Code after the loop block is no longer executed, and the loop continues.
For (int I = 0; I <4; I ++)
{
If (I = 2)
Continue;
Console. WriteLine (I );
}
The print result is 0 1 3. The print will be skipped here.
From smart dummies