# Global vs local variables

I’m following “Learning Processing” by Daniel Shiffman, a great book. But when it comes to explaining some of the exercises it is not always clear.

The question is: "Predict the result of the following two sketches. After 100 frames, what will the screen look like? Test your theory by running them."

For the question the reader gets three options: a black screen, a grey screen and a white screen.

We get a) "global variable"

``````int count = 0;
void setup() {
size(200,200);
}
void draw() {
count = count + 1;
background(count);
}
``````

and b) "local variable"

``````void setup() {
size(200,200);
}
void draw() {
int count = 0;
count = count + 1;
background(count);
}
``````

How is that the latter, with the local variable, remains black, while for the other the loop does work?

The line code which sets the background color is: background(count), which is the last line of code within draw().
In the second example (b), the variable “count” is set to 0 every frame and then incremented to 1. Therefore the background at the end of each frame will be 1 (practically black).
In the first example (a), the variable “count” is global, meaning that its value at the beginning of each frame will be the one passed at the end of the previous frame. Since it is incremented by one each frame, the background after 100 frames will be 100 (one of the green colors);
The following sketch will show a changing background from 0 to the frame 100. You can modify the variable maxCount up to 255 to see the background reached at the frame equal to maxCount.

int count = 0;
int maxCount=100;

void setup() {
size(200,200);
}

void draw() {
count = count + 1;
delay(30);
if(count>maxCount) {
count=maxCount;
}
background(count);
}

My error: Ignore the “(one of the green colors);” in my previous reply.

Local variables & parameters “die” when their method/function ends/returns.