News:

Let's find out together what makes a PIC Tick!

Main Menu

Gosub within a procedure

Started by joesaliba, Jan 05, 2023, 10:19 AM

Previous topic - Next topic

joesaliba

Hi,

As per the title, can I call a subroutine from a procedure?

Thanks

Joe

top204

Yes.

A procedure can be thought of as a wrapped subroutine with optional parameters, so a call to a standard subroutine can be made from within it to a global or local label name. This is because a Gosub/Return has no special needs and is just a Call/Return in assembler. For example, try the code listing below:

Main:
   
    TestProc()
   
'---------------------------------------------------------------------------------
' A test procedure to call a subroutine inside a procedure
'
Proc TestProc()
    HRSOut "Hello "
    GoSub SubLabel          ' Call the subroutine and have the EndProc return from it
    ExitProc                ' Exit the procedure early so it does not fall into the subroutine
   
SubLabel:
    HRSOutLn "World"
EndProc

On a serial terminal it will display "Hello World"

Pepe

Is it not necessary to put return after HRSOutLn "World"?

Yasin

I think you overlooked that before "Gosub" there is HRSOut "Hello "

top204

QuoteIs it not necessary to put return after HRSOutLn "World"?

An EndProc is a Return, but it returns from a procedure and marks the end of the procedure, so the subroutine will still have a return at the end of it. However, the compiler's optimiser kicks in with the previous code listing and uses Bra mnemonics instead of Call/Return, so it makes the code tighter, faster and more efficient with a device's small call stack.

joesaliba

Thanks Les for the information.

QuoteA procedure can be thought of as a wrapped subroutine with optional parameters

Therefore I can also call a subroutine outside of a procedure, just take care of the stack.

Regards

Joe