"Out of Stack Space" Error Using GOSUB to Label Outside of SUB (77580)






This article was previously published under Q77580

SUMMARY

The BC.EXE compiler will accept and compile programs that use a GOSUB statement inside a SUB or FUNCTION to jump to a line number or label that was previously defined in the program but outside that SUB or FUNCTION. However, the QB.EXE and QBX.EXE environments correctly detect this error and report a "Label Not Defined" error message.

Even though the BC.EXE compiler will accept the use of GOSUB to transfer to labels outside of the current SUB or FUNCTION, it is recommended that you do not do this, as it can result in behavior that may be very difficult to debug.

This information applies to Microsoft QuickBasic version 4.5 for MS-DOS and the Microsoft Basic Professional Development System (PDS) versions 7.0 and 7.1 for MS-DOS and MS OS/2.

MORE INFORMATION

The following is a code example demonstrating how the use of GOSUB to exit a SUB or FUNCTION may cause problems:
CALL SecondSub
END

SUB FirstSub()
  Label1:
  PRINT "In Gosub routine"
  CALL sub2
  RETURN
END SUB

SUB SecondSub()
  PRINT "Performing Gosub"
  GOSUB Label1
  PRINT "Returned from Gosub"
END SUB
				
This program will compile with BC.EXE, but will not run in the QB.EXE or QBX.EXE environment. Even though the program may be successfully compiled, the resulting executable will quickly run out of stack space. The CALL before the RETURN in FirstSub is causing another call to SecondSub to be made before the last one has finished, resulting in an accumulation of calls on the stack, until an "Out of Stack Space" error occurs.

Modification Type: Minor Last Reviewed: 1/9/2003
Keywords: KB77580