Subroutines

Cards (12)

  • A subroutine is a named section of code that can be called by writing the subroutine's name in a program statement.
  • Subroutines can also be referred to as procedures or functions.
  • A procedure is a set of instructions that will be executed when the procedure is called, whilst a function also contains a set of instructions that will be executed when the function is called and it will also return a value when it has finished executing.
  • Using subroutines makes the code more readable and reusable, as the code is broken into smaller sections. Most programming languages come with a standard library of built-in subroutines to perform common functions, but also have the capability to allow the programmer to write their own custom subroutines.
  • Each subroutine must be designed to carry out a specific task and the identifier should reflect its purpose. It is important to choose meaningful identifiers so that your program is self-documenting.
  • A subroutine can be called anywhere in a program, including in other subroutines.
  • The use of a main subroutine is a widely used convention in programming and in particular in procedural programming. When used, the main subroutine is the starting point for the program. The position of the main subroutine within the overall program will depend on several factors. For example, in Python, it will be found at the bottom of the program because of the way that the code is interpreted when it is run.
  • The flow of control differs when a subroutine call is encountered. Instead of running statements one after another, the program transfers control ‘out of line’ to the subroutine, and the code in the subroutine is executed.
  • Inside a subroutine, variables declared within the subroutine cannot be accessed outside the subroutine (unless passed as parameters).
  • When a subroutine returns, execution continues from where it left off inside the calling routine.
  • As your programs become larger, using subroutines allows you to organise the program into smaller chunks that are easier to understand, debug and maintain. 
  • A global variable is one that can be accessed and changed throughout the whole program, while local variables have their scope limited to one subroutine.