Difference between revisions of "Goto"

From Lazarus wiki
Jump to navigationJump to search
(“real-world” example; added discouragement to use that statement)
m (wording)
Line 22: Line 22:
 
     {$I+}
 
     {$I+}
 
   ExitNoErr:
 
   ExitNoErr:
end;</syntaxhighlight>According to the value of {{Doc|package=RTL|unit=system|identifier=returnnilifgrowheapfails|text=<syntaxhighlight enclose="none" lang="pascal">returnNilIfGrowHeapFails</syntaxhighlight>}} {{Doc|package=RTL|unit=system|identifier=getmem|text=<syntaxhighlight enclose="none" lang="pascal">getMem</syntaxhighlight>}} possibly may return [[Nil|<syntaxhighlight enclose="none" lang="pascal">nil</syntaxhighlight>]].
+
end;</syntaxhighlight>
Instead of placing ''everything'' in “success”-branch, a <syntaxhighlight enclose="none" lang="pascal">goto</syntaxhighlight> instruction was chosen.
+
According to the value of {{Doc|package=RTL|unit=system|identifier=returnnilifgrowheapfails|text=<syntaxhighlight enclose="none" lang="pascal">returnNilIfGrowHeapFails</syntaxhighlight>}} {{Doc|package=RTL|unit=system|identifier=getmem|text=<syntaxhighlight enclose="none" lang="pascal">getMem</syntaxhighlight>}} possibly may return [[Nil|<syntaxhighlight enclose="none" lang="pascal">nil</syntaxhighlight>]].
 +
Instead of placing ''everything'' in a “success”-branch, a couple <syntaxhighlight enclose="none" lang="pascal">goto</syntaxhighlight> instructions were chosen.
  
 
[[category:Pascal]]
 
[[category:Pascal]]
 
[[Category:Control Structures]]
 
[[Category:Control Structures]]

Revision as of 19:48, 7 March 2018

Deutsch (de) English (en) français (fr) русский (ru)

goto is an unconditional jump to a previously declared label (either before or after the goto command).

Usage of goto in high-level programming languages such as Pascal is highly discredited, since control structures of all sorts are available. The last situation a goto is agreed with bad grace is a significant system error, where a “graceful exit” is better than causing a system breakdown.

As an example, here an excerpt from FPC's code base rtl/inc/extres.inc:

324procedure InitResources;
328label ExitErrMem, ExitErrFile, ExitNoErr;
329begin
339  ResHeader:=GetMem(sizeof(TExtHeader));
340  if ResHeader=nil then goto ExitErrFile;
366  goto ExitNoErr;
367
368  ExitErrMem:
369    FreeMem(ResHeader);
370    ResHeader:=nil;
371  ExitErrFile:
372    {$I-}
373    Close(fd);
374    {$I+}
375  ExitNoErr:
376end;

According to the value of returnNilIfGrowHeapFails getMem possibly may return nil. Instead of placing everything in a “success”-branch, a couple goto instructions were chosen.