Statements and Exceptions - Pdf 63

chapter
6
Statements and Exceptions
I
n C#, statements fall into one of three categories: labeled, declaration, and
embedded. This is shown by the following EBNF definition:
EBNF
Stmt = LabeledStmt | DeclStmt | EmbeddedStmt .
Embedded statements include the full gamut of conditional, iterative, and transfer state-
ments that one would expect in any high-level language. Additional constructs for mutual
exclusion and the use of resources are also provided.
In this chapter, we first present one type of embedded statement called the block
statement. Declaration statements and all other embedded statements are then discussed
with particular emphasis on the exception-handling mechanism of C#. Because of their
limited use and appeal, labeled statements are only described in the narrow context of the
goto and switch statements.
6.1 Block Statement
A block is an embedded statement that encloses zero or more statements within a pair of
opening and closing braces:
EBNF
Block = "{" Stmts? "}" .
Each statement in a block is executed in sequence, but the block itself returns no value.
Although a block is not required for only one statement, it is a useful practice to enclose
Tip
a single statement within braces, as would become required if additional statements were
added. For example, if a debugging Write is added to this statement:
if(x>0)
x = temp;
107
108
Chapter 6: Statements and Exceptions

...
for(intn=0;n<8;n++) {
// n is in the scope of the for
...
}
...
char c; // Declaration closer to its related code
...
}

6.3 Embedded Statements
109
Finally, any variable that is used before declaration or is accessed outside its scope
generates a compilation error.
6.3 Embedded Statements
Embedded statements in C# include many of the well-known constructs in C/C++ and
Java, such as block statements (described previously), expression statements, empty state-
ments, selection statements, and iteration statements. A summary of these statements and
others in C# are listed in the following EBNF definition and described in the sections that
follow.
EBNF
EmbeddedStmt = ExprStmt | EmptyStmt | Block | SelectionStmt
| IterationStmt | JumpStmt | TryStmt | CheckedStmt
| UncheckedStmt | LockStmt | UsingStmt | YieldStmt .
6.3.1 Expression and Empty Statements
An expression statement is simply an expression with a semicolon at the end. However,
only the following types of expressions can become statements:

Method invocations,


Otherwise, EmbeddedStmt2 is executed whenever present. Two variations of the if
statement, with and without the else part, are illustrated in the following single
example:
bool directionUp;
...
if (directionUp) { // If statement with an else part
if (++count > max) { // Nested if statement without an else part
count = min;
return true;
}
} else {
if (--count < min) { // Nested if statement without an else part
count = max;
return true;
}
}
return false;
Another variation of the if statement uses the else if clause to select one of many alterna-
tives. In the following example, this variation selects one of four alternatives based on the
value of an operator character. A similar example using the switch statement is presented
in the next subsection.
char operator;
...
if (operator == ‘+’) {
...
} else if (operator == ‘-’) {
...
} else if (operator == ‘*’) {
...


...
switch (op) {
case ‘+’: Console.WriteLine(" = {0}", int1 + int2); break;
case ‘-’: Console.WriteLine(" = {0}", int1 - int2); break;
case ‘x’: goto case ‘*’; // To obtain a fall through
case ‘*’: Console.WriteLine(" = {0}", int1 * int2); break;
case ‘/’: if ( int2 != 0 )
Console.WriteLine(" = {0}", int1 / int2);
else
Console.WriteLine("Divide by zero");
break;
default: Console.WriteLine("Invalid operator: must be+-*x/");
break;
}
112
Chapter 6: Statements and Exceptions

6.3.3 Iteration Statements
Iteration statements, or loops, allow a single statement or block to be executed repeat-
edly. The loop condition is a boolean expression that determines when to terminate the
loop. C# provides four kinds of loops: while, do-while, for, and foreach statements.
while Statement
The syntax of the while loop is:EBNF
WhileStmt = "while" "(" BooleanExpr ")" EmbeddedStmt .
EmbeddedStmt is executed zero or more times until the BooleanExpr evaluates to false.
Example:
Console.Write("Countdown: ");
int sec = 9;
while ( sec >= 0 )
Console.Write("{0} ", sec--);

ForInitializer = LocalVarDecl | StmtExprList .
ForCondition = BooleanExpr .
ForIterator = StmtExprList .
Example (giving the same output):
Console.Write("Countdown: ");
for (int sec = 9; sec >= 0; --sec)
Console.Write("{0} ", sec);
Console.WriteLine("... Go!");
An infinite for loop that prints dots:
for (;;)
Console.Write(".");
is equivalent to the following while statement:
while (true)
Console.Write(".");
foreach Statement
The syntax of the foreach loop is:
EBNF
ForeachStmt = "foreach" "(" Type Identifier "in" Expr ")" EmbeddedStmt .
The foreach statement enumerates the elements of a given collection and executes the
embedded statement for each one. The Type and Identifier declare a read-only itera-
tion variable to be used locally within the scope of the embedded statement. During the
loop execution, this iteration variable represents a collection element. A compilation error
114
Chapter 6: Statements and Exceptions

occurs if the variable is (1) modified via assignment or the ++ and -- operators or (2) passed
as a ref or out parameter.
Example:
int[] evenNumbers={2,4,6,8};
foreach (int n in evenNumbers)


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status