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

CHAPTER 9 STATEMENTS

Labeled Statements

A labeled statement consists of an identifier, followed by a colon, followed by a statement. It has the following form:

Identifier: Statement

A labeled statement is executed exactly as if the label were not there and consisted of just the

Statement part.

Adding a label to a statement allows control to be transferred to the statement from another part of the code.

Labeled statements are allowed only inside blocks.

Labels

Labels have their own declaration space, so the identifier in a labeled statement can be any valid identifier—including those that might be declared in an overlapping scope, such as local variables or parameter names.

For example, the following code shows the valid use of a label with the same identifier as a local variable:

{

 

 

int xyz = 0;

//

Variable xyz

...

 

 

xyz: Console.WriteLine("No problem.");

//

Label xyz

}

 

 

There are restrictions, however. The identifier cannot be either

The same as another label identifier with an overlapping scope

A keyword

259

CHAPTER 9 STATEMENTS

The Scope of Labeled Statements

Labeled statements cannot be seen (or accessed) from outside the block in which they are declared. The scope of a labeled statement is

The block in which it is declared

Any blocks nested inside that block

For example, the code on the left of Figure 9-9 contains several nested blocks, with their scopes marked. There are two labeled statements declared in scope B of the program: increment and end.

The shaded portions on the right of the figure show the areas of the code in which the labeled statements are in scope.

Code in scope B, and all the nested blocks, can see and access the labeled statements.

Code from any of the inner scopes can jump out to the labeled statements.

Code from outside (scope A, in this case) cannot jump into a block with a labeled statement.

Figure 9-9. The scope of labels includes nested blocks.

260

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