Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Understanding and Using the Goto Delphi Statement

Title: Understanding and Using the Goto Delphi Statement As most programming languages, Delphi supports the Goto statement. A Goto statement transfers program execution to the statement marked by the specified label. Read this again! Goto does not "ask questions", it simply forces a jump to some other location in the code block. When badly used Goto could transform your code into a non-readable piece of junk. According to the "Are you using the Goto statement in Delphi" poll, it seems 40% of Delphi developers do not even know Goto exists in Delphi. Another 40% would have a very low opinion on you if they would see Goto in your Delphi code. Be it bad or good, Goto is in Delphi and you might need to use it, or at least need to understand how it works. Here's a code block that might produce some very nasty, unpredictable effects: var label : skipOut; label : breakCodeFlow; j,k : integer; begin breakCodeFlow: for j := 0 to 10 do begin for k := 0 to 10 do begin if Something_Related_To_J_and_K then begin GOTO skipOut; end; end; end; skipOut: //continue program execution here... if j = 0 then begin //some code block GOTO breakCodeFlow; end; A goto statement needs a label ("skipOut" and "breakCodeFlow") to be defined in the var section. Luckily, even though Goto can be used for bad ideas, there are some restrictions in using Goto: You can "Goto" only inside the same scope block. You cannot "Goto" out of a function of procedure. You cannot jump into or out of a try/finally or try/except block. Note that if you need, for example, to skip out of a "for loop" you should be using the Break statement, or other RTL's flow control routines (Abort, Break, Continue, Exit). Anyway, read How I (Almost) Ended Up Using Goto in Delphi code. For some additional ideas of why and when and how and why not and (...) about using the Goto Delphi statement, read the "Are you using the Goto Delphi statement" poll comments