Pages

Sunday, 14 June 2015

Jump Control

Jump Control

break Statement

The break is use to exit execution from innermost enclosing block. For example:
string[] names = { "John","Jacob", "Aaron","Abdul","Sayudi","Ansorul","Yang","Jimmy","Robert","Jones"};
string myName = "Yang";
for (int i = 0; i < names.Length; ++i)
{
 Console.WriteLine("Searching " + myName + " at index:" + i);
 if (names[i] == myName)
 {
  Console.WriteLine(myName + " Found at index: " + i);
  break;
 }
}
If code compiled and run, will display:
Searching Yang at index:0
Searching Yang at index:1
Searching Yang at index:2
Searching Yang at index:3
Searching Yang at index:4
Searching Yang at index:5
Searching Yang at index:6
Yang Found at index: 6

continue Statement

The continue statement causes program execution to go to the top of the innermost enclosing loop. Example below is code fragment to search odd number between 0 to 10.
for (int i = 0; i <= 10; ++i)
{
 if (i % 2 == 0)
  continue;
 Console.WriteLine(i + " is odd number");
}
The code will resulting:
1 is odd number
3 is odd number
5 is odd number
7 is odd number
9 is odd number

label and goto Statement

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.
There are restrictions, however. The identifier cannot be either
  • A keyword
  • The same as another label identifier with an overlapping scope
string myLabel = "label1"
myLabel:    //valid Label declaration
 ....
otherLabel:   //valid label declaration
 ....
for:    //invalid label, for is a Keyword
    ....
myLabel:   //invalid label, myLabel already declared
 ....
The goto statement unconditionally transfers control to a labeled statement. Its general form is the following, where Identifier is the identifier of a labeled statement:
goto [Identifier] ;
For example, the following code shows the simple use of a goto statement:
bool thingsAreFine;
while (true)
{
 thingsAreFine = GetNuclearReactorCondition();
 if ( thingsAreFine )
  Console.WriteLine("Things are fine.");
 else
  goto NotSoGood;
}
NotSoGood: Console.WriteLine("We have a problem.");
The goto statement must be within the scope of the labeled statement.
  • A goto statement can jump to any labeled statement within its own block or can jump out to any block in which it is nested.
  • A goto statement cannot jump into any blocks nested within its own block.
Using the goto statement is strongly discouraged because it can lead to code that is poorly structured and difficult to debug and maintain. Edsger Dijkstra’s 1968 letter to the Communications of the ACM, entitled “Go To Statement Considered Harmful,” was an important contribution to computer science; it was one of the first published descriptions of the pitfalls of using the goto statement.

0 comments:

Post a Comment