Blog|Meta Topics|Advanced Topics

Software Technology: Scope

Assumed Knowledge
Learning Outcomes
  • Identify different scopes in a program
  • Identify which variable declarations correspond to each variable use.

Why scope?

We have made it to the point where we might have two totally separate variables with the same name. In truth, we got to that point earlier, but it was unlikely to occur. Now we are in a world where it will happen a lot. Lets look at an example where this might naturally occur.

Here is a program that will draw a UFO travelling across the screen at the top, and a shadow of that UFO tracking below it. It has three different variables in it. Each declartion of xpos creates a whole new slot in memory and there are three different declarations. one on line 1, one on line 15 and one on line 20.

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

void setup(){
  size(400,400);
  xpos = 0;
}

void draw(){
  background(255);
  ufoAt(xpos);
  reflectionAt(xpos);
  xpos = xpos + 1;
}

void ufoAt(int xpos){
  fill(255, 43, 98);
  ellipse(xpos, 10, 40, 20);
}

void reflectionAt(int xpos){
  fill(0,0,0);
  ellipse(xpos, height, 40,20);
}

The question that is answered by scope rules is when I use the variable name xpos, which declaration will I get?

Since the declaration and creation of these memory slots is dynamic, lets take a look at the running program to understand better.

The scoping rules

  • Each curly brace introduces a new scope (not exactly true, see below, but it will do for now).
  • A variable is only alive in the scope in which it is declared.
  • If more than one variable with a certain name is alive, then the one declared in the smallest enclosing scope is the one that is used.

As a side note, these rules mean you can’t have two variables with the same name declared in exactly the same scope, and your compiler will enforce this and tell you when you have done so.

Not exactly true?

For loop, conditions, and functions, the curly brace indicates a new scope, but the scope really starts before the curly brace, at the start of the expression.