Pages

Sunday, 14 June 2015

Statements

Statements

The statements in C# are very similar to those of C and C++.
  • A statement is a source code instruction describing a type or telling the program to perform an action.
  • There are three major categories of statements:
    • Declaration statements: Statements that declare types or variables
    • Embedded statements: Statements that perform actions or manage flow of control
    • Labeled statements: Statements to which control can jump
You can find declaration statements in previous section.Now we'll cover up the embedded statements, which do not declare types, variables, or instances. Instead, they use expressions and flow control constructs to work with the objects and variables that have been declared by the declaration statements.
  • Simple statement consists of an expression followed by a semicolon.
  • Block is a sequence of statements enclosed by matching curly braces. The enclosed statements can include the following:
    • Declaration statements
    • Embedded statements
    • Labeled statements
    • Nested blocks
The following code gives examples of each:
const double PI = 3.1416;    // Simple declaration
double area;       // Simple declaration
{ // Start of a block
double radius = 20.0;    // Simple declaration
area = PI * radius * radius;  // Embedded statement
volume: high = 30;   // Labeled statement
...
{ // Start of a nested block
 double volume = area * high; //Embedded statement
 ...
} // End of nested block
} // End of outer block

Empty Statements

An empty statement consists of just a semicolon. You can use an empty statement at any position where the syntax of the language requires an embedded statement but your program logic does not require any action.
 
 if( maxValue > newValue )
  ; // Empty statement, Do Nothing
 else
  maxValue = newValue; //Simple statement
 

Expression Statements

Expressions is a statements that not only return values, but they can also have side effects.
  • A side effect is an action that affects the state of the program.
  • Many expressions are evaluated only for their side effects.
For example:
x = 10
This does the following two things:
  • The expression assigns the value on the right of the operator to the memory location referenced by variable x. Although this is probably the main reason for the statement, this is considered the side effect.
  • After setting the value of x, the expression returns with the new value of x. But there is nothing to receive this return value, so it is ignored.
The whole reason for evaluating the expression is to achieve the side effect.

0 comments:

Post a Comment