Subroutine, procedure, function

In programming subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. Then this unit can be used in program wherever that particular task necessary.

In different programming languages, a subroutine may be called a procedure, a function, a routine, a method, or a subprogram.

Recursion is when a subroutine calls itself.

subroutine's data

Typically, arguments (parameters) and local variables are stored on the stack. So in infinite recursions, a stack overflow error may appear.

Advantages

Advantages of using subroutines:

  • decomposing a complex programming task into simpler steps
  • improving traceability
  • reducing duplicate code within a program
  • enabling reuse of code across multiple programs
  • dividing a large programming task among various programmers, or various stages of a project
  • hiding implementation details from users of the subroutine
  • Improving readability of code by replacing a block of code with a function call where a descriptive function name serves to describe the block of code. This makes the calling code concise and readable even if the function is not meant to be reused.