Что такое стейтмент в программировании

Урок №8. Структура программ

Компьютерная программа — это последовательность инструкций, которые сообщают компьютеру, что ему нужно сделать.

Стейтменты

Cтейтмент (англ. «statement») — это наиболее распространенный тип инструкций в программах. Это и есть та самая инструкция, наименьшая независимая единица в языке С++. Стейтмент в программировании — это то же самое, что и «предложение» в русском языке. Мы пишем предложения, чтобы выразить какую-то идею. В языке C++ мы пишем стейтменты, чтобы выполнить какое-то задание. Все стейтменты в языке C++ заканчиваются точкой с запятой.

Есть много разных видов стейтментов в языке C++. Рассмотрим самые распространенные из них:

int х — это стейтмент объявления (англ. «statement declaration»). Он сообщает компилятору, что х является переменной. В программировании каждая переменная занимает определенное число адресуемых ячеек в памяти в зависимости от её типа. Минимальная адресуемая ячейка — байт. Переменная типа int может занимать до 4 байт, т.е. до 4 адресуемых ячеек памяти. Все переменные в программе должны быть объявлены, прежде чем использованы. Мы детально поговорим о переменных на следующих уроках.

std::cout — это стейтмент вывода (англ. «output statement»). Мы выводим значение переменной х на экран.

Выражения

Функции

В языке C++ стейтменты объединяются в блоки — функции. Функция — это последовательность стейтментов. Каждая программа, написанная на языке C++, должна содержать главную функцию main(). Именно с первого стейтмента, находящегося в функции main(), и начинается выполнение всей программы. Функции, как правило, выполняют конкретное задание. Например, функция max() может содержать стейтменты, которые определяют большее из заданных чисел, а функция calculateGrade() может вычислять среднюю оценку студента по какой-либо дисциплине.

Библиотеки

Библиотека — это набор скомпилированного кода (например, функций), который был «упакован» для повторного использования в других программах. С помощью библиотек можно расширить возможности программ. Например, если вы пишете игру, то вам придется подключать библиотеки звука или графики (если вы самостоятельно не хотите их создавать).

Язык C++ не такой уж и большой, как вы могли бы подумать. Тем не менее, он идет в комплекте со Стандартной библиотекой С++, которая предоставляет дополнительный функционал. Одной из наиболее часто используемых частей Стандартной библиотеки C++ является библиотека iostream, которая позволяет выводить данные на экран и обрабатывать пользовательский ввод.

Пример простой программы

Теперь, когда у вас есть общее представление о том, что такое стейтменты, функции и библиотеки, давайте рассмотрим еще раз программу «Hello, world!»:

Строка №1: Специальный тип инструкции, который называется директивой препроцессора. Директивы препроцессора сообщают компилятору, что ему нужно выполнить определенное задание. В этом случае мы говорим компилятору, что хотели бы подключить содержимое заголовочного файла к нашей программе. Подключение заголовочного файла дает нам возможность использовать функционал библиотеки iostream, что, в свою очередь, позволяет выводить нам данные на экран.

Строка №2: Пустое пространство, которое игнорируется компилятором.

Строка №3: Объявление главной функции main().

Строки №4 и №7: Указываем компилятору область функции main(). Всё, что находится между открывающей фигурной скобкой в строке №4 и закрывающей фигурной скобкой в строке №7 — считается содержимым функции main().

Строка №6: Оператор возврата return. Когда программа завершает свое выполнение, функция main() передает обратно в операционную систему значение, которое указывает на результат выполнения программы: успешно ли прошло выполнение программы или нет.

Синтаксис и синтаксические ошибки

Как вы, должно быть, знаете, в русском языке все предложения подчиняются правилам грамматики. Например, каждое предложение должно заканчиваться точкой. Правила, которые регулируют построение предложений, называются синтаксисом. Если вы не поставили точку и записали два предложения подряд, то это является нарушением синтаксиса русского языка.

Язык C++ также имеет свой синтаксис: правила написания кода/программ. При компиляции вашей программы, компилятор отвечает за то, чтобы ваша программа соответствовала правилам синтаксиса языка C++. Если вы нарушили правила, то компилятор будет ругаться и выдаст вам ошибку.

Например, давайте посмотрим, что произойдет, если мы не укажем в конце стейтмента точку с запятой:

Источник

Statements

C# provides a variety of statements. Most of these statements will be familiar to developers who have programmed in C and C++.

The embedded_statement nonterminal is used for statements that appear within other statements. The use of embedded_statement rather than statement excludes the use of declaration statements and labeled statements in these contexts. The example

results in a compile-time error because an if statement requires an embedded_statement rather than a statement for its if branch. If this code were permitted, then the variable i would be declared, but it could never be used. Note, however, that by placing i ‘s declaration in a block, the example is valid.

End points and reachability

Every statement has an end point. In intuitive terms, the end point of a statement is the location that immediately follows the statement. The execution rules for composite statements (statements that contain embedded statements) specify the action that is taken when control reaches the end point of an embedded statement. For example, when control reaches the end point of a statement in a block, control is transferred to the next statement in the block.

If a statement can possibly be reached by execution, the statement is said to be reachable. Conversely, if there is no possibility that a statement will be executed, the statement is said to be unreachable.

the second invocation of Console.WriteLine is unreachable because there is no possibility that the statement will be executed.

A warning is reported if the compiler determines that a statement is unreachable. It is specifically not an error for a statement to be unreachable.

To determine whether a particular statement or end point is reachable, the compiler performs flow analysis according to the reachability rules defined for each statement. The flow analysis takes into account the values of constant expressions (Constant expressions) that control the behavior of statements, but the possible values of non-constant expressions are not considered. In other words, for purposes of control flow analysis, a non-constant expression of a given type is considered to have any possible value of that type.

the Console.WriteLine invocation is considered reachable, even though, in reality, it will never be executed.

The block of a function member is always considered reachable. By successively evaluating the reachability rules of each statement in a block, the reachability of any given statement can be determined.

the reachability of the second Console.WriteLine is determined as follows:

There are two situations in which it is a compile-time error for the end point of a statement to be reachable:

Blocks

A block permits multiple statements to be written in contexts where a single statement is allowed.

A block consists of an optional statement_list (Statement lists), enclosed in braces. If the statement list is omitted, the block is said to be empty.

A block may contain declaration statements (Declaration statements). The scope of a local variable or constant declared in a block is the block.

A block is executed as follows:

The statement list of a block is reachable if the block itself is reachable.

The end point of a block is reachable if the block is empty or if the end point of the statement list is reachable.

A block that contains one or more yield statements (The yield statement) is called an iterator block. Iterator blocks are used to implement function members as iterators (Iterators). Some additional restrictions apply to iterator blocks:

Statement lists

A statement list consists of one or more statements written in sequence. Statement lists occur in blocks (Blocks) and in switch_blocks (The switch statement).

A statement list is executed by transferring control to the first statement. When and if control reaches the end point of a statement, control is transferred to the next statement. When and if control reaches the end point of the last statement, control is transferred to the end point of the statement list.

A statement in a statement list is reachable if at least one of the following is true:

The end point of a statement list is reachable if the end point of the last statement in the list is reachable.

The empty statement

An empty_statement does nothing.

An empty statement is used when there are no operations to perform in a context where a statement is required.

Execution of an empty statement simply transfers control to the end point of the statement. Thus, the end point of an empty statement is reachable if the empty statement is reachable.

An empty statement can be used when writing a while statement with a null body:

Also, an empty statement can be used to declare a label just before the closing » > » of a block:

Labeled statements

A labeled_statement permits a statement to be prefixed by a label. Labeled statements are permitted in blocks, but are not permitted as embedded statements.

A labeled statement declares a label with the name given by the identifier. The scope of a label is the whole block in which the label is declared, including any nested blocks. It is a compile-time error for two labels with the same name to have overlapping scopes.

A label can be referenced from goto statements (The goto statement) within the scope of the label. This means that goto statements can transfer control within blocks and out of blocks, but never into blocks.

Labels have their own declaration space and do not interfere with other identifiers. The example

is valid and uses the name x as both a parameter and a label.

Execution of a labeled statement corresponds exactly to execution of the statement following the label.

Declaration statements

A declaration_statement declares a local variable or constant. Declaration statements are permitted in blocks, but are not permitted as embedded statements.

Local variable declarations

A local_variable_declaration declares one or more local variables.

The local_variable_type of a local_variable_declaration either directly specifies the type of the variables introduced by the declaration, or indicates with the identifier var that the type should be inferred based on an initializer. The type is followed by a list of local_variable_declarators, each of which introduces a new variable. A local_variable_declarator consists of an identifier that names the variable, optionally followed by an » = » token and a local_variable_initializer that gives the initial value of the variable.

In the context of a local variable declaration, the identifier var acts as a contextual keyword (Keywords).When the local_variable_type is specified as var and no type named var is in scope, the declaration is an implicitly typed local variable declaration, whose type is inferred from the type of the associated initializer expression. Implicitly typed local variable declarations are subject to the following restrictions:

The following are examples of incorrect implicitly typed local variable declarations:

The value of a local variable is obtained in an expression using a simple_name (Simple names), and the value of a local variable is modified using an assignment (Assignment operators). A local variable must be definitely assigned (Definite assignment) at each location where its value is obtained.

The scope of a local variable declared in a local_variable_declaration is the block in which the declaration occurs. It is an error to refer to a local variable in a textual position that precedes the local_variable_declarator of the local variable. Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.

A local variable declaration that declares multiple variables is equivalent to multiple declarations of single variables with the same type. Furthermore, a variable initializer in a local variable declaration corresponds exactly to an assignment statement that is inserted immediately after the declaration.

corresponds exactly to

In an implicitly typed local variable declaration, the type of the local variable being declared is taken to be the same as the type of the expression used to initialize the variable. For example:

The implicitly typed local variable declarations above are precisely equivalent to the following explicitly typed declarations:

Local constant declarations

A local_constant_declaration declares one or more local constants.

The type of a local_constant_declaration specifies the type of the constants introduced by the declaration. The type is followed by a list of constant_declarators, each of which introduces a new constant. A constant_declarator consists of an identifier that names the constant, followed by an » = » token, followed by a constant_expression (Constant expressions) that gives the value of the constant.

The type and constant_expression of a local constant declaration must follow the same rules as those of a constant member declaration (Constants).

The value of a local constant is obtained in an expression using a simple_name (Simple names).

The scope of a local constant is the block in which the declaration occurs. It is an error to refer to a local constant in a textual position that precedes its constant_declarator. Within the scope of a local constant, it is a compile-time error to declare another local variable or constant with the same name.

A local constant declaration that declares multiple constants is equivalent to multiple declarations of single constants with the same type.

Expression statements

An expression_statement evaluates a given expression. The value computed by the expression, if any, is discarded.

Not all expressions are permitted as statements. In particular, expressions such as x + y and x == 1 that merely compute a value (which will be discarded), are not permitted as statements.

Execution of an expression_statement evaluates the contained expression and then transfers control to the end point of the expression_statement. The end point of an expression_statement is reachable if that expression_statement is reachable.

Selection statements

Selection statements select one of a number of possible statements for execution based on the value of some expression.

The if statement

The if statement selects a statement for execution based on the value of a boolean expression.

An else part is associated with the lexically nearest preceding if that is allowed by the syntax. Thus, an if statement of the form

An if statement is executed as follows:

The switch statement

The switch statement selects for execution a statement list having an associated switch label that corresponds to the value of the switch expression.

The governing type of a switch statement is established by the switch expression.

The constant expression of each case label must denote a value that is implicitly convertible (Implicit conversions) to the governing type of the switch statement. A compile-time error occurs if two or more case labels in the same switch statement specify the same constant value.

There can be at most one default label in a switch statement.

A switch statement is executed as follows:

If the end point of the statement list of a switch section is reachable, a compile-time error occurs. This is known as the «no fall through» rule. The example

is valid because no switch section has a reachable end point. Unlike C and C++, execution of a switch section is not permitted to «fall through» to the next switch section, and the example

results in a compile-time error. When execution of a switch section is to be followed by execution of another switch section, an explicit goto case or goto default statement must be used:

Multiple labels are permitted in a switch_section. The example

is valid. The example does not violate the «no fall through» rule because the labels case 2: and default: are part of the same switch_section.

The «no fall through» rule prevents a common class of bugs that occur in C and C++ when break statements are accidentally omitted. In addition, because of this rule, the switch sections of a switch statement can be arbitrarily rearranged without affecting the behavior of the statement. For example, the sections of the switch statement above can be reversed without affecting the behavior of the statement:

Like the string equality operators (String equality operators), the switch statement is case sensitive and will execute a given switch section only if the switch expression string exactly matches a case label constant.

The statement_lists of a switch_block may contain declaration statements (Declaration statements). The scope of a local variable or constant declared in a switch block is the switch block.

The statement list of a given switch section is reachable if the switch statement is reachable and at least one of the following is true:

The end point of a switch statement is reachable if at least one of the following is true:

Iteration statements

Iteration statements repeatedly execute an embedded statement.

The while statement

The while statement conditionally executes an embedded statement zero or more times.

A while statement is executed as follows:

Within the embedded statement of a while statement, a break statement (The break statement) may be used to transfer control to the end point of the while statement (thus ending iteration of the embedded statement), and a continue statement (The continue statement) may be used to transfer control to the end point of the embedded statement (thus performing another iteration of the while statement).

The end point of a while statement is reachable if at least one of the following is true:

The do statement

The do statement conditionally executes an embedded statement one or more times.

A do statement is executed as follows:

Within the embedded statement of a do statement, a break statement (The break statement) may be used to transfer control to the end point of the do statement (thus ending iteration of the embedded statement), and a continue statement (The continue statement) may be used to transfer control to the end point of the embedded statement.

The embedded statement of a do statement is reachable if the do statement is reachable.

The end point of a do statement is reachable if at least one of the following is true:

The for statement

The for statement evaluates a sequence of initialization expressions and then, while a condition is true, repeatedly executes an embedded statement and evaluates a sequence of iteration expressions.

The for_initializer, if present, consists of either a local_variable_declaration (Local variable declarations) or a list of statement_expressions (Expression statements) separated by commas. The scope of a local variable declared by a for_initializer starts at the local_variable_declarator for the variable and extends to the end of the embedded statement. The scope includes the for_condition and the for_iterator.

The for_condition, if present, must be a boolean_expression (Boolean expressions).

The for_iterator, if present, consists of a list of statement_expressions (Expression statements) separated by commas.

A for statement is executed as follows:

Within the embedded statement of a for statement, a break statement (The break statement) may be used to transfer control to the end point of the for statement (thus ending iteration of the embedded statement), and a continue statement (The continue statement) may be used to transfer control to the end point of the embedded statement (thus executing the for_iterator and performing another iteration of the for statement, starting with the for_condition).

The embedded statement of a for statement is reachable if one of the following is true:

The end point of a for statement is reachable if at least one of the following is true:

The foreach statement

The foreach statement enumerates the elements of a collection, executing an embedded statement for each element of the collection.

The compile-time processing of a foreach statement first determines the collection type, enumerator type and element type of the expression. This determination proceeds as follows:

Otherwise, determine whether the type X has an appropriate GetEnumerator method:

Otherwise, check for an enumerable interface:

is then expanded to:

An implementation is permitted to implement a given foreach-statement differently, e.g. for performance reasons, as long as the behavior is consistent with the above expansion.

The placement of v inside the while loop is important for how it is captured by any anonymous function occurring in the embedded_statement.

The body of the finally block is constructed according to the following steps:

If there is an implicit conversion from E to the System.IDisposable interface, then

If E is a non-nullable value type then the finally clause is expanded to the semantic equivalent of:

Otherwise the finally clause is expanded to the semantic equivalent of:

except that if E is a value type, or a type parameter instantiated to a value type, then the cast of e to System.IDisposable will not cause boxing to occur.

Otherwise, if E is a sealed type, the finally clause is expanded to an empty block:

Otherwise, the finally clause is expanded to:

The local variable d is not visible to or accessible to any user code. In particular, it does not conflict with any other variable whose scope includes the finally block.

The following example prints out each value in a two-dimensional array, in element order:

The output produced is as follows:

Jump statements

Jump statements unconditionally transfer control.

The location to which a jump statement transfers control is called the target of the jump statement.

When a jump statement occurs within a block, and the target of that jump statement is outside that block, the jump statement is said to exit the block. While a jump statement may transfer control out of a block, it can never transfer control into a block.

Execution of jump statements is complicated by the presence of intervening try statements. In the absence of such try statements, a jump statement unconditionally transfers control from the jump statement to its target. In the presence of such intervening try statements, execution is more complex. If the jump statement exits one or more try blocks with associated finally blocks, control is initially transferred to the finally block of the innermost try statement. When and if control reaches the end point of a finally block, control is transferred to the finally block of the next enclosing try statement. This process is repeated until the finally blocks of all intervening try statements have been executed.

the finally blocks associated with two try statements are executed before control is transferred to the target of the jump statement.

The output produced is as follows:

The break statement

A break statement cannot exit a finally block (The try statement). When a break statement occurs within a finally block, the target of the break statement must be within the same finally block; otherwise, a compile-time error occurs.

A break statement is executed as follows:

Because a break statement unconditionally transfers control elsewhere, the end point of a break statement is never reachable.

The continue statement

A continue statement cannot exit a finally block (The try statement). When a continue statement occurs within a finally block, the target of the continue statement must be within the same finally block; otherwise a compile-time error occurs.

A continue statement is executed as follows:

Because a continue statement unconditionally transfers control elsewhere, the end point of a continue statement is never reachable.

The goto statement

The goto statement transfers control to a statement that is marked by a label.

The target of a goto identifier statement is the labeled statement with the given label. If a label with the given name does not exist in the current function member, or if the goto statement is not within the scope of the label, a compile-time error occurs. This rule permits the use of a goto statement to transfer control out of a nested scope, but not into a nested scope. In the example

a goto statement is used to transfer control out of a nested scope.

The target of a goto case statement is the statement list in the immediately enclosing switch statement (The switch statement), which contains a case label with the given constant value. If the goto case statement is not enclosed by a switch statement, if the constant_expression is not implicitly convertible (Implicit conversions) to the governing type of the nearest enclosing switch statement, or if the nearest enclosing switch statement does not contain a case label with the given constant value, a compile-time error occurs.

The target of a goto default statement is the statement list in the immediately enclosing switch statement (The switch statement), which contains a default label. If the goto default statement is not enclosed by a switch statement, or if the nearest enclosing switch statement does not contain a default label, a compile-time error occurs.

A goto statement cannot exit a finally block (The try statement). When a goto statement occurs within a finally block, the target of the goto statement must be within the same finally block, or otherwise a compile-time error occurs.

A goto statement is executed as follows:

Because a goto statement unconditionally transfers control elsewhere, the end point of a goto statement is never reachable.

The return statement

The return statement returns control to the current caller of the function in which the return statement appears.

A return statement with an expression can only be used in a function member that computes a value, that is, a method with a non-void result type, the get accessor of a property or indexer, or a user-defined operator. An implicit conversion (Implicit conversions) must exist from the type of the expression to the return type of the containing function member.

Return statements can also be used in the body of anonymous function expressions (Anonymous function expressions), and participate in determining which conversions exist for those functions.

It is a compile-time error for a return statement to appear in a finally block (The try statement).

A return statement is executed as follows:

Because a return statement unconditionally transfers control elsewhere, the end point of a return statement is never reachable.

The throw statement

The throw statement throws an exception.

A throw statement with no expression can be used only in a catch block, in which case that statement re-throws the exception that is currently being handled by that catch block.

Because a throw statement unconditionally transfers control elsewhere, the end point of a throw statement is never reachable.

When an exception is thrown, control is transferred to the first catch clause in an enclosing try statement that can handle the exception. The process that takes place from the point of the exception being thrown to the point of transferring control to a suitable exception handler is known as exception propagation. Propagation of an exception consists of repeatedly evaluating the following steps until a catch clause that matches the exception is found. In this description, the throw point is initially the location at which the exception is thrown.

If the try block of S encloses the throw point and if S has one or more catch clauses, the catch clauses are examined in order of appearance to locate a suitable handler for the exception, according to the rules specified in Section The try statement. If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.

Otherwise, if the try block or a catch block of S encloses the throw point and if S has a finally block, control is transferred to the finally block. If the finally block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the finally block, processing of the current exception is continued.

If an exception handler was not located in the current function invocation, the function invocation is terminated, and one of the following occurs:

If the current function is non-async, the steps above are repeated for the caller of the function with a throw point corresponding to the statement from which the function member was invoked.

If the current function is async and task-returning, the exception is recorded in the return task, which is put into a faulted or cancelled state as described in Enumerator interfaces.

If the current function is async and void-returning, the synchronization context of the current thread is notified as described in Enumerable interfaces.

If the exception processing terminates all function member invocations in the current thread, indicating that the thread has no handler for the exception, then the thread is itself terminated. The impact of such termination is implementation-defined.

The try statement

The try statement provides a mechanism for catching exceptions that occur during execution of a block. Furthermore, the try statement provides the ability to specify a block of code that is always executed when control leaves the try statement.

There are three possible forms of try statements:

When a catch clause specifies both an exception_specifier with an identifier, an exception variable of the given name and type is declared. The exception variable corresponds to a local variable with a scope that extends over the catch clause. During execution of the exception_filter and block, the exception variable represents the exception currently being handled. For purposes of definite assignment checking, the exception variable is considered definitely assigned in its entire scope.

Unless a catch clause includes an exception variable name, it is impossible to access the exception object in the filter and catch block.

A catch clause that does not specify an exception_specifier is called a general catch clause.

In order to locate a handler for an exception, catch clauses are examined in lexical order. If a catch clause specifies a type but no exception filter, it is a compile-time error for a later catch clause in the same try statement to specify a type that is the same as, or is derived from, that type. If a catch clause specifies no type and no filter, it must be the last catch clause for that try statement.

Within a catch block, a throw statement (The throw statement) with no expression can be used to re-throw the exception that was caught by the catch block. Assignments to an exception variable do not alter the exception that is re-thrown.

the method F catches an exception, writes some diagnostic information to the console, alters the exception variable, and re-throws the exception. The exception that is re-thrown is the original exception, so the output produced is:

If the first catch block had thrown e instead of rethrowing the current exception, the output produced would be as follows:

It is a compile-time error for a return statement to occur in a finally block.

A try statement is executed as follows:

Control is transferred to the try block.

When and if control reaches the end point of the try block:

If an exception is propagated to the try statement during execution of the try block:

If an exception is thrown during execution of a finally block, and is not caught within the same finally block, the exception is propagated to the next enclosing try statement. If another exception was in the process of being propagated, that exception is lost. The process of propagating an exception is discussed further in the description of the throw statement (The throw statement).

The try block of a try statement is reachable if the try statement is reachable.

A catch block of a try statement is reachable if the try statement is reachable.

The finally block of a try statement is reachable if the try statement is reachable.

The end point of a try statement is reachable if both of the following are true:

The checked and unchecked statements

The checked and unchecked statements are used to control the overflow checking context for integral-type arithmetic operations and conversions.

The checked statement causes all expressions in the block to be evaluated in a checked context, and the unchecked statement causes all expressions in the block to be evaluated in an unchecked context.

The checked and unchecked statements are precisely equivalent to the checked and unchecked operators (The checked and unchecked operators), except that they operate on blocks instead of expressions.

The lock statement

The lock statement obtains the mutual-exclusion lock for a given object, executes a statement, and then releases the lock.

The expression of a lock statement must denote a value of a type known to be a reference_type. No implicit boxing conversion (Boxing conversions) is ever performed for the expression of a lock statement, and thus it is a compile-time error for the expression to denote a value of a value_type.

A lock statement of the form

where x is an expression of a reference_type, is precisely equivalent to

except that x is only evaluated once.

While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads is blocked from obtaining the lock until the lock is released.

Locking System.Type objects in order to synchronize access to static data is not recommended. Other code might lock on the same type, which can result in deadlock. A better approach is to synchronize access to static data by locking a private static object. For example:

The using statement

The using statement obtains one or more resources, executes a statement, and then disposes of the resource.

A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown. If the resource is of type dynamic it is dynamically converted through an implicit dynamic conversion (Implicit dynamic conversions) to IDisposable during acquisition in order to ensure that the conversion is successful before the usage and disposal.

A using statement of the form

corresponds to one of three possible expansions. When ResourceType is a non-nullable value type, the expansion is

In either expansion, the resource variable is read-only in the embedded statement, and the d variable is inaccessible in, and invisible to, the embedded statement.

An implementation is permitted to implement a given using-statement differently, e.g. for performance reasons, as long as the behavior is consistent with the above expansion.

A using statement of the form

When a resource_acquisition takes the form of a local_variable_declaration, it is possible to acquire multiple resources of a given type. A using statement of the form

is precisely equivalent to a sequence of nested using statements:

The example below creates a file named log.txt and writes two lines of text to the file. The example then opens that same file for reading and copies the contained lines of text to the console.

Since the TextWriter and TextReader classes implement the IDisposable interface, the example can use using statements to ensure that the underlying file is properly closed following the write or read operations.

The yield statement

The yield statement is used in an iterator block (Blocks) to yield a value to the enumerator object (Enumerator objects) or enumerable object (Enumerable objects) of an iterator or to signal the end of the iteration.

yield is not a reserved word; it has special meaning only when used immediately before a return or break keyword. In other contexts, yield can be used as an identifier.

There are several restrictions on where a yield statement can appear, as described in the following.

The following example shows some valid and invalid uses of yield statements.

An implicit conversion (Implicit conversions) must exist from the type of the expression in the yield return statement to the yield type (Yield type) of the iterator.

A yield return statement is executed as follows:

The next call to the enumerator object’s MoveNext method resumes execution of the iterator block from where it was last suspended.

A yield break statement is executed as follows:

Because a yield break statement unconditionally transfers control elsewhere, the end point of a yield break statement is never reachable.

Источник

Понравилась статья? Поделиться с друзьями:

Не пропустите наши новые статьи:

  • что такое стейт в программировании
  • что такое стейдж в программировании
  • Что такое статическая типизация в программировании
  • что такое статическая библиотека в программировании
  • Что такое статистические методы класса в программировании

  • Операционные системы и программное обеспечение
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest
    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии