The goto Statement
C# enables you to label lines of code and then jump straight to them using the goto statement. This has its benefits and problems. The main benefit is that it ’ s a simple way to control what code is executed when. The main problem is that excessive use of this technique can result in difficult-to-understand spaghetti code.
The goto statement is used as follows:
goto < labelName > ;
Labels are defined as follows:
< labelName > :
For example, consider the following:
int myInteger = 5; goto myLabel; myInteger += 10; // never executed myLabel: Console.WriteLine("myInteger = {0}", myInteger);
Execution proceeds as follows:
- myInteger is declared as an int type and assigned the value 5 .
- The goto statement interrupts normal execution and transfers control to the line marked
myLabel :. - The value of myInteger is written to the console.
In fact, if you try this out in an application, this is noted in the Error List window as a warning when you try to compile the code, labeled “ Unreachable code detected , ” along with location details. You will also see a wavy green line under myInteger on the unreachable line of code. goto statements have their uses, but they can make things very confusing indeed. The following example shows some spaghetti code arising from the use of goto :
start: int myInteger = 5; goto addVal; writeResult: Console.WriteLine("myInteger = {0}", myInteger); goto start; addVal: myInteger += 10; goto writeResult;