Skip to content

SpecificationVII · Subroutines

7.1

Declaring subprograms

A subprogram is a named piece of program: it is written once and used as many times as needed.

Markdown version

7.1.1 How to write it

Subroutine «nombre»(«parámetros») ⟦As «tipo»⟧
  «instrucciones»
EndSubroutine
Function «resultado» <- «nombre»(«parámetros»)
  Define «resultado» As «tipo»;
  «instrucciones»
EndFunction

7.1.2 How it works

Subprograms are declared next to the main algorithm, never inside it nor inside another subprogram. Order does not matter: you can call one that is written further down.

ProgramA procedure and a function

Subroutine Saludar(nombre As String)
  Write "Hola, ", nombre;
EndSubroutine

Subroutine Doble(n As Integer) As Integer
  Return n * 2;
EndSubroutine

Algorithm Principal
  Saludar("Ana");
  Write Doble(21);
EndAlgorithm

Output

Hola, Ana
42

The program finishes normally.

Figure 7.1-1.A subprogram seen from outside: the arguments go in, the result comes out. What happens inside is hidden.

A box called Doble. The argument 21 goes in on the left and the result 42 comes out on the right.

The Function form is handy when the result is built up little by little. It has no Return with a value: it returns whatever its result variable holds.

ProgramFunction with a result variable

Function area <- AreaRectangulo(base As Real, alto As Real)
  Define area As Real;
  area <- base * alto;
EndFunction

Algorithm Principal
  Write AreaRectangulo(3.0, 4.5);
EndAlgorithm

Output

13.5

The program finishes normally.

Inside a subprogram everything that works in the algorithm works too: declarations, Read, Write, decisions and loops. The variables it declares are local: nobody else sees them.

In short

  • Subroutine declares a subprogram; with As type it returns a value.
  • Function returns what its result variable holds and is pure.
  • They are declared next to the algorithm, in any order.
  • Their variables are local.