Chapter 12: Arithmetic

 

The goto Statement as a Replacement for the break Statement

An alternative formulation for the break statement is the infamous goto statement. The Visual Studio C# compiler will accept a goto statement, despite the fact that some snooty programmers consider the use of the statement to be vulgar and uneducated. All we can say is, it does what it is supposed to do. Replace break with goto MAUI and at line IA050, type MAUI:. Now the code breaks away from this for loop as soon as the first case of 77 is found. The final form looks like this:

 IA043:     for(int kk = 0 ; kk < 12 ; kk++) IA044:     { IA045:       if(intArrayNumbers[kk] == intReferenceNumber)              { IA047:         intLocation = kk; IA048:         goto MAUI;              }            } IA050B:    MAUI: 

This next example is a common occurrence with for statements. The number of loops the loop will make is not hard coded into the loop but is determined just before the loop is entered (in this case, a statement intEndLineNumber = 2):

 IA042:   int intLocation = -1; IA043:   for(int kk=0;kk<intEndLineNumber ; kk++) IA044:   { IA045:     if(intArrayNumbers[kk] == intReferenceNumber) intLocation = kk;           } 

Note that intReferenceNumber comes from code above this snippet, and it equals 77 this time.

This loop will execute twice ” once when kk = 0 and once when kk = 1 (since intEndLineNumber equals 2).

For the next example, intEndLineNumber comes from above as 0. What happens now?

 IA042:   int intLocation = -1; IA043:   for(int tt=0;tt<intEndLineNumber ; tt++)          { IA045:     if(intArrayNumbers[tt] == intReferenceNumber) intLocation = tt;          } 

The loop will not execute since 0 is not less than 0 the first time the test tt < intEndLineNumber is made in line IA043.

If the text tt < intEndLineNumber were changed to tt <= intEndLineNumber (tt less than or equal to intEndLineNumber), the loop would execute because 0 is less than or equal to 0 the first time through the loop.

 


Unlocking Microsoft C# V 2.0 Programming Secrets
Unlocking Microsoft C# V 2.0 Programming Secrets (Wordware Applications Library)
ISBN: 1556220979
EAN: 2147483647
Year: 2005
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net