Sequence 3.1 – Variables

Pablo Oliveira & Samuel Tardieu

What is a variable?

The compiler job is to ensure consistency between uses and modifications of the variable regardless of where it is stored.

How are variables declared in Tiger?

let var a : int := 3   /* Explicit typing */
    var b := 4         /* Implicit typing */
in
  a := a * 2;          /* Now a contains 6 */
  a + b                /* Evaluates as 10 */
end

Variable lifetime

let var a := 3      /* a exists after this line */
    var b := a + 4  /* b exists after this line */
in
/* a and b can be used here */
end  /* a and b do longer exist after this line */

Variable lookup

let var a := 3
    var b := a + 4  /* a from L.1 is used */
in
  let var a := 7
  in
    a := a * 3;     /* a from L.4 is used */
    a + 1
  end
end

Variable lookup and types

let var a := "Hello"
in
  let var a := 3 in
/* Here, a is an integer */
  end;  /* Integral a lifetime end */
  print(a);  /* This prints the string Hello */
end

Functions also create a scope

let var a := 3
    function f(a: string) = print(a)
    var b := a + 4
in  /* The innermost scope contains a, f, and b */
  f("The value of b is ");
  print_int(b)
end

Example of multi-level lookups

let var a := 3
    var b := 4
in
  let var a := 10
  in
    a + b /* Uses a from L.4 and b from L.2: 14 */
  end
end

Mutually recursive functions

let function f(a: int): int = g(a+1)
    function g(a: int): int = f(a-1)
    var b := 4
    function h(a: int): int = f(a) + g(a) + b
in
  f(3)
end

Conclusion