Difference between revisions of "Subroutine"

From SEGGER Wiki
Jump to: navigation, search
m
m
Line 13: Line 13:
 
</syntaxhighlight>
 
</syntaxhighlight>
   
===How does it work in practice===
+
===How does it work in practice?===
  +
First of all, most architectures have a call instruction. "Call" is the logical name. Unfortunately, it is not always called that way. Some other names are
TBD
 
  +
* JSR (Jump SubRoutine, on 6202 and related architectures)
 
  +
* BL or BLX (Branch linked or Branch Linked with Mode switch) on ARM architectures
  +
A call instruction transfers control to an other subroutine by loading the address of the first instruction of the subroutine into the [[PC]] memorizing the current PC
  +
(the address of the next instruction to execute). Memorizing the return address can happen in 2 ways basically:
  +
By saving it on the [[stack]] or in a dedicated register, typically called RA (Return Address register) or LR (Link register, ARM architectures)
 
===Inlining===
 
===Inlining===
   

Revision as of 21:18, 23 June 2019

A subroutine is a piece of program code that is designed to be called by a program. It is not a stand-alone application, so it is not usable in itself. I an real world application, the bulk of the program consists of subroutines. A subroutine can take parameters and return a value.

Let's look at a simple example of a subroutine:

int Max(int a, int b)
  if (a > b) {
    return a;
  }
  return b;
}

How does it work in practice?

First of all, most architectures have a call instruction. "Call" is the logical name. Unfortunately, it is not always called that way. Some other names are

  • JSR (Jump SubRoutine, on 6202 and related architectures)
  • BL or BLX (Branch linked or Branch Linked with Mode switch) on ARM architectures

A call instruction transfers control to an other subroutine by loading the address of the first instruction of the subroutine into the PC memorizing the current PC (the address of the next instruction to execute). Memorizing the return address can happen in 2 ways basically: By saving it on the stack or in a dedicated register, typically called RA (Return Address register) or LR (Link register, ARM architectures)

Inlining

FAQs

What is the difference between a function and a subroutine?

The simple answer is: It is the same. Some people will disagree to that, saying that a function operates on local values (the parameters) only, that a function has to return a value. That would mean every function is a subroutine, but not every subroutine is a function. In any case, let's just assume they are the same and it is not worth arguing about.