Incorporating Goto: $Goto and $Label

Top  Previous  Next

The $If syntax alternatives above only allows conditional execution of a single line of GAMS commands (actually that line can contain several individual commands separated by one or more ; ).  This can be an obstacle and can be overcome using the $Goto and $Label syntax.  Specifically, one can incorporate commands like

 

$Goto labelname

 

within a $If conditional or in it's own line in the GMS file that causes branching to a place where the following command appears

 

$Label labelname

 

which identifies a place to which the code can branch.

Note $IFTHEN and variants can get used if one wishes to jump multiple statements.

Example:

(goto.gms)

scalar y /1/;

$Setglobal gg

$If setglobal gg $goto yesgg

y=y+3;

display y;

$label yesgg

display y;

*after yesgg

$If not setglobal gg $goto nogg

y=y/14;

display y;

$label nogg

 

The effect on the code is

 

3  scalar y /1/;

6  *after yesgg

8  y=y/14;

9  display y;

 

Note the red lines are suppressed because the true $If causes the $Goto to skip around.