Programming style - GOTO or GOSUB ?


Closed Thread
Results 1 to 8 of 8

Hybrid View

  1. #1
    Join Date
    Sep 2007
    Location
    USA, CA
    Posts
    271


    Did you find this post helpful? Yes | No

    Default

    Quote Originally Posted by AndrewC View Post
    I'm looking for GO GO Guru

    In pbp, what are the tradeoffs between using GOTO or GOSUB to branch to different areas of code ? Does one use more memory than the other ? Is there a limit to how many GOSUBs that can be nested ?

    I have some distant memory that you should only use GOTO within a specific (sub)routine and it is better to use GOSUB rather than GOTO to jump to / use a specific code segment. Obviously as well GOSUB will return you to where you started whereas with GOTO you can jump A>B>C>A.

    Also, I often use a WHILE - WEND loop for 3 button menu control, is it better to use GOTO or GOSUB here:

    WHILE Switch_1 = 1
    IF Switch_2 = 0 then GOSUB Label X
    IF Switch_3 = 0 then GOSUB Label Y
    WEND


    Thanks, Andrew
    Using Gosub or Goto is NOT a style question. It is a FLOW question.

    You use Gosub when you want to Return as soon as the routine is done.

    Use Goto to depart your routine, "never" to return. (Although you can start it over later.)

  2. #2
    Join Date
    Feb 2006
    Location
    Brussels, Belgium
    Posts
    104


    Did you find this post helpful? Yes | No

    Default

    So should there be any difference in the amount of memory used when coding ? Empirically they seem to use the same amount of compiled memory.

  3. #3
    Join Date
    Nov 2003
    Location
    Wellton, U.S.A.
    Posts
    5,924


    Did you find this post helpful? Yes | No

    Default

    GOSUB will use just a little more space.

    Example...
    I am working a piece of code with two sub routines that when finished will be part of the main code, a flow through thing. I have them as GOSUBs now for testing, easily comment out a GOSUB to test one or the other.

    As the code stands currently with the GOSUBs and RETURNs in place 3528 bytes are used.
    When I remove the GOSUBs and RETURNs 3516 bytes are used.

    The extra space is small compared to having a "function" written over and over.
    The way to have the smallest code is this respect is to have one loop, but if you have an ADC that needs read more than once in the main loop a GOSUB/RETURN will be much smaller than having the ADC written twice... or more.
    Dave
    Always wear safety glasses while programming.

Members who have read this thread : 1

You do not have permission to view the list of names.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts