Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 9 STATEMENTS

Jump Statements

When the flow of control reaches jump statements, program execution is unconditionally transferred to another part of the program. The jump statements are the following:

break

continue

return

goto

throw

This chapter covers the first four of these statements. The throw statement is explained in Chapter 11.

The break Statement

Earlier in this chapter you saw the break statement used in the switch statement. It can also be used in the following statement types:

for

foreach

while

do

In the body of one of these statements, break causes execution to exit the innermost enclosing loop. For example, the following while loop would be an infinite loop if it relied only on its test

expression, which is always true. But instead, after three iterations of the loop, the break statement is encountered, and the loop is exited.

int x = 0; while( true )

{

x++;

if( x >= 3 ) break;

}

257

CHAPTER 9 STATEMENTS

The continue Statement

The continue statement causes program execution to go to the top of the innermost enclosing loop of the following types:

while

do

for

foreach

For example, the following for loop is executed five times. In the first three iterations, it encounters the continue statement and goes directly back to the top of the loop, missing the WriteLine statement at the bottom of the loop. Execution only reaches the WriteLine statement during the last two iterations.

for( int x=0; x<5; x++ )

//

Execute loop five times

{

 

 

 

if( x < 3 )

//

The first three times

continue;

//

Go

directly back to top of loop

// This line is only reached when x

is

3 or greater.

Console.WriteLine("Value of x is {0}",

x);

}

 

 

 

This code produces the following output:

Value of x is 3

Value of x is 4

The following code shows an example of a continue statement in a while loop. This code produces the same output as the preceding for loop example.

int x = 0;

 

 

while(

x < 5

)

 

{

 

 

 

if(

x < 3

)

 

{

x++;

 

 

 

 

 

}

continue;

// Go back to top of loop

 

 

 

// This line is reached only when x is 3 or greater. Console.WriteLine("Value of x is {0}", x);

x++;

}

258

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]