Skip to content

SpecificationV · Declarations and statements

5.1

Declaring variables with Define

Define creates variables: named, typed boxes where the program keeps a value that can change.

Markdown version

5.1.1 How to write it

Define «nombre» As «tipo» ⟦<- «valor inicial»⟧;
Define «nombre», «nombre» As «tipo»;

5.1.2 How it works

A variable is a name bound to a place in memory. Define creates that place with the given type. With an initial value, the value is stored at once; without one, the box stays empty until the first assignment.

ProgramVariables in a backpack

Algorithm Mochila
  Define libros, cuadernos As Integer;
  Define nombre As String <- "Leo";
  libros <- 3;
  cuadernos <- libros * 2;
  Write nombre, " lleva ", libros, " libros y ", cuadernos, " cuadernos";
EndAlgorithm

Output

Leo lleva 3 libros y 6 cuadernos

The program finishes normally.

  1. 1Define libros, cuadernos As Integer; creates two empty boxes.

  2. 2Define nombre As String <- "Leo"; creates a box that already has a value.

  3. 3libros <- 3; fills the first box.

  4. 4cuadernos <- libros * 2; reads libros and stores 6.

Figure 5.1-1.Every Define creates a box with a name and a type. Those without an initial value start empty.

Three boxes in memory: libros and cuadernos, of type Integer, start empty; nombre, of type String, starts with "Leo". Then libros receives 3 and cuadernos receives 6, computed by reading libros.

An empty box has no default value: it is not 0 nor "". Before running, the engine checks that a variable that may be empty is never read.

Every variable declared with Define can be changed later. For a value that never changes there is [Constant](#declaraciones.constante).

In short

  • Define creates one or more variables of a type.
  • The initial value is optional and only valid with one name.
  • Without an initial value, the variable starts empty, not at zero.
  • A name is not repeated in the same scope.