Scope

  • variables and functions declared in a particular scope are visible and accessible only within that scope and its nested scopes, but not outside of it

    1. Local variables

      • The variables defined within a particular function or block of code
      • The are only accessible within that function or block and its nested scopes
    2. Nonlocal variables

      • The variables defined in a parent function
      • They are accessible within nested functions

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        int g;

        void f(int a){
        int b;
        // g is nonlocal (global)
        // a, b are local
        }

        int main(){
        int x = 0;
        // g is nonlocal (global)
        // x is local

        for(int i = 0; i < 10; i++){
        int y = 0;
        // g is nonlocal (global)
        // x is nonlcoal
        // i, y are local
        }
        return 0;
        }

Static Scope

  • It done before run time
  • It searches locally, then proceeds to increasingly larger enclosing scopes until the given variable name is found

    • Static ancestors: the enclosing static scope that contain it
    • Static parent: the nearest static ancestors

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      x = "global"

      def outer():
      x = "outer"

      def inner():
      x = "inner"
      print(x) # inner

      inner()
      print(x) # outer

      outer()
      print(x) # global
  • Evaluation:
    • Advantages:
      1. Easy to read and understand
      2. Relatively fast
      3. Static type checking is possible
    • Disadvantages:
      1. Too much access is possible
      2. Inconvenience
        • As the program evolves, the initial structure is destoryed and local variables often become global, even subprograms also toward become global rather than nested

Blocks

  • A method of creating static scopes inside a program unit (C++, Java cannot define a function inside a function)

  • Compound statement is a statement sequence that groups more statements into a single statement (in a brace{})

    • each compound statement have declarations which defined a new scope

      1
      2
      3
      4
      5
      6
      7
      8
      public static void main(String[] args){
      int x = 0;
      if(true){
      int y = 1;
      System.out.println(y); // 1
      }
      System.out.println(y); // y is not visible
      }
  • Nested block

    • Reusing name in nested blocks is only legal in C and C++
      1
      2
      3
      4
      5
      6
      7
      8
      int main(){
      int x = 0;
      {
      int x = 1;
      std::cout << x << std::endl; // 1
      }
      std::cout << x << std::endl; // 0
      }
      1
      2
      3
      4
      5
      6
      public static void main(String[] args){
      int x = 0;
      {
      int x = 1; // error - already defined
      }
      }

Declaration Order

  • Some old languages (C89) require variable declaration at the top of the function

    • In C89 compiler, the variable should be declare before the loop
      1
      2
      3
      4
      5
      6
      int main(){
      // int i;
      for(int i = 0; i < 8; i++){ // error
      printf("hi ");
      }
      }
  • C99, C++, Java, C# allow variable declarations appear anywhere

    • In C99, C++, Java, the scope of all local variables is from the declaration to the end of the block

      1
      2
      3
      4
      5
      6
      7
      // OK in Java
      public static void main(String[] args){
      {
      int x = 0;
      }
      int x = 1;
      }
    • But in C#, the scope of any variable declared in a block is the whole block

      1
      2
      3
      4
      5
      6
      7
      // Not ok in C#
      static void Main(string[] args) {
      {
      int x = 0;
      }
      int x = 1;
      }

Global Scope

  • The scope in which variables and functions are visible to the entire program (including in other files)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // File 1
    static int i = 99; // CAN define it again in other file
    int g = 100; // CANNOT define it again in other file
    extern int j; // extern needed, if you want to declare a variable from other file

    int main(){
    std::cout << i << std::endl; // 99
    std::cout << j << std::endl; // 777
    std::cout << g << std::endl; // 100
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // File 2
    static int i = 1234;
    int j = 777;
    int g = 0; // illegal

    int main(){
    std::cout << i << std::endl; // 1234
    std::cout << j << std::endl; // 777
    std::cout << g << std::endl; // Compilation error: 'g' has already been defined
    }

Python Scope

  • Global variable
    • It can be referenced in all functions
    • It can be assigned if it has been declared to be global using the keyword global in the function
      1
      2
      3
      4
      5
      6
      7
      g = "global"
      def f():
      global g
      g = "local"
      print("from f(), ", g) # local
      f()
      print("from glocal, ", g) # local
  • Nonlocal variable
    • It can be referenced in the inner functions
    • It can be assigned if it has been declared to be nonlocal using the keyword nonlocal in the function
    • NOTED: The `nonlocal` only refers to the nearest static ancestors
    • NOTED: The nonlocal only works for nonlocal variables, which means it cannot refer to a global variable
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      def sub1():
      print("sub1")
      x = "modified at sub1"

      def sub2():
      # nonlocal x
      print("sub2")
      x = "modified at sub2"

      def sub3():
      nonlocal x # goes into the static parent (sub2)
      print("sub3")
      x = "modified at sub3"

      sub3()
      print("x from sub2:", x) # x from sub2: modified at sub3

      sub2()
      print("x from sub1:", x) # x from sub1: modified at sub1

      sub1()

Dynamic Scope

  • The scope of a variable is determined by the order of function calls at runtime rather than by the static structure of the program

    • Temporal
    • Can only be determined at runtime
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      function big(){
      var x = "hehe"

      function sub1(){
      var x = "haha"
      }

      function sub2(){
      sub1()
      var y = x
      var z = "hoho"
      }

      sub2()
      print(x)
      }
      big()

      // static scoping: hehe
      // dynamic scoping: haha
  • Evaluation:

    • Advantages:
      1. Convenience
        • Variables from the caller are implicitly visible in the callee
    • Disadvantages:
      1. Reliability
        • The variables are visibile to all subprograms it calls
        • Impossible to statically type check
      2. Hard to understand
        • the variable value can be different every time
      3. Costly runtime

Referencing Environments

  • A data structure that stores all variable names that are visible at the statement

  • Static-scoped language:

    • local variables + all visible variables in all enclosing scopes
  • Dynamic-scoped language

    • local variables + all visible variables in all active subprograms in calling sequence
    • active subprograms<: the execution has begun but not yet terminated
  • Practice 1: Python Scoping

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    g = "global doge"
    def sub1():
    h = "husky"
    # Point (1)
    def sub2():
    global g
    c = "corgi"
    # Point (2)
    def sub3():
    nonlocal c
    g = "meow"
    # Point (3)
Point Referencing Environment
(1) local h (reference & assignment), global g (reference only)
(2) local c (reference & assignment), global g (reference and assignment), nonlocal h (reference only)
(3) local g (reference & assignment), nonlocal c (reference and assignment), nonlocal h (reference only)
  • Practice 2: Dynamic Scoping
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    function sub1(){
    var a, b
    //Point (1)
    }
    function sub2(){
    var b, c
    //Point (2)
    sub1()
    }
    function main(){ //suppose main() is the program entry point
    var c, d
    //Point (3)
    sub2()
    }
Point Referencing Environment
(1) a and b (sub1), c (sub2), d (main)
(2) b and c (sub2), d (main)
(3) c and d (main)

Named Constants

  • A variable that is bound to a value only once

  • The binding of values can be either static or dynamic

  • Advantages

    1. Readibility
    2. Reliability
    3. Possibility to parameterize a program
  • Syntax:

    • Java

      • final: dynamically bound
    • C++

      1. const: dynamically bound
      2. constexp: statically bound, must be evaluated at compile time
    • C#

      1. readonly: dynamically bound
      2. const: statically bound, must be evaluated at compile time

Scope & Lifetime

  • Scope and lifetime are often closely related, but are different concepts
  • Example:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    void f(){
    static int x; // static storage
    }
    int main(){
    for(int i = 0; i < 10; i++){
    printf("ha ");
    }
    f();
    x = 0; // cannot be accessed
    return;
    }
    • Lifetime: x is static storage because of the keyword static, because all static storage variables are already existed in the data region
    • Scope: x cannot be accessed in the main function because of its scope, which is not related to the static storage