Topic 3 · Class activity 5 · Week 8 · Wednesday

Scope and Shadowing

Predict the output, draw the scope stack, break exitScope, then work out what dynamic scoping would have printed.

Format pairsTime 40 min

The point

Shadowing is easy to describe and easy to get wrong. Predict, then verify, then break it on purpose.

Do this

  1. Predict the output line by line before running anything.
    int n;
    int twice(int n) { return n + n; }
    int main() {
        int m;
        n = 10;
        m = twice(3);
        print(n);
        print(m);
        { int n; n = 99; print(n); }
        print(n);
        return 0;
    }
  2. Draw the scope stack at each print. Which entry does the lookup find, and how many scopes did it search? Name the rule you are applying.
  3. Run it without -q, find the scope traces, and reconcile.
  4. Break it. Make exitScope() a no-op. Predict what goes wrong, then confirm. Is the error the one you predicted?
  5. Break it the other way. Restore that, and make lookup search only the OUTERMOST scope. Which of the two symbol tables did you just break — the visibility one or the storage one? How can you tell from the symptom?
  6. Theory question. Our language is statically scoped. Write down what the program above would print under dynamic scoping, and say which line reveals the difference.

Deliverable

Your line-by-line prediction; scope-stack diagrams; a paragraph on each sabotage; and your dynamic-scoping answer. Feeds Lab Questions 11 and 16.