Unit-2.3 Statements
Unit-2.3 Statements
Overview
High C++ fidelity
if, while, do require bool condition
goto can’t jump into blocks
switch statement
No fall-through
foreach statement
checked and unchecked statements
Expression void Foo() {
statements i == 1; // error
must do work }
Statements
Overview
Statement lists Loop Statements
Block statements
while
do
Labeled statements for
Declarations foreach
Constants
Jump Statements
Variables break
Expression statements continue
checked, unchecked goto
lock return
using throw
Conditionals Exception handling
if try
switch throw
Statements
Syntax
Statements are terminated with a
semicolon (;)
Just like C, C++ and Java
Block statements { ... } don’t need a semicolon
Statements
Syntax
Comments
// Comment a single line, C++ style
/* Comment multiple
lines,
C style
*/
Statements
Statement Lists & Block Statements
Statement list: one or more statements in
sequence
Block statement: a statement list delimited by
braces { ... } static void Main() {
F();
G();
{ // Start block
H();
; // Empty statement
I();
} // End block
}
Statements
Variables and Constants
int a;
int b = 2, c = 3;
a = 1;
Console.WriteLine(a + b + c);
}
Statements
Variables and Constants
The scope of a variable or constant runs
from the point of declaration to the end of
the enclosing block
Statements
Variables and Constants
Within the scope of a variable or constant it is an
error to declare another variable or constant with
the same name
{
int x;
{
int x; // Error: can’t hide variable x
}
}
Statements
Variables
Variables must be assigned a value before they
can be used
Explicitly or automatically
Called definite assignment
Automatic assignment occurs for static fields,
class instance fields and array elements
void Foo() {
string s;
Console.WriteLine(s); // Error
}
Statements
Labeled Statements & goto
goto can be used to transfer control within or
out of a block, but not into a nested block
static void Find(int value, int[,] values,
out int row, out int col) {
int i, j;
for (i = 0; i < values.GetLength(0); i++)
for (j = 0; j < values.GetLength(1); j++)
if (values[i, j] == value) goto found;
throw new InvalidOperationException(“Not found");
found:
row = i; col = j;
}
Statements
Expression Statements
Statements must do work
Assignment, method call, ++, --, new
int i = 0;
while (i < 5) {
...
i++;
int i = 0;
}
do {
...
i++;
}
while (i < 5); while (true) {
...
}
Statements
for Statement