Global vs. Local Variables – Variable Scope
- Up until this moment, any time that we have used a variable, we have declared it at the top of our program above setup( ) –> these are global variables
- Global variables can be referred to anywhere in your program (setup, draw, mousePressed, etc).
- Not all information needs to be remembered for the entirety of your program. Sometimes we only need to hang onto a piece of information for a little while, and then we can throw it away.
- A local variable declared within a block of code is only available for use inside that specific block of code where it was declared. (Only inside of setup, for instance. Or inside of an IF statement).
//global variable
int x = 0;
void setup(){
size(200,200);
x = 25;
}
void draw(){
rect(x, 100, 100, 100);
}
//local variable void setup(){ size(200,200); } void draw(){ int x = 25; rect(x, 100, 100, 100); } //NOTE- SETUP DOES NOT KNOW ABOUT VARIABLE X
We see local variables in FOR loops! The FOR loop is a nifty shortcut for commonly occurring while loops where one value is being incremented (or decremented) repeatedly.
Remember the while loop —
int x = 0; //THE INITIAL CONDITION while(x < 25) { //THE BOOLEAN TEST EXIT STRATEGY rect(x, 100,100,100); x = x + 1; //THE INCREMENT }
FOR loops allow us to do all of this in one line of code
for(int x = 0; x < 25; x++){ rect(x, 100,100,100); }
int x = 0 declares a local variable x and sets its initial condition (it is common to use the name “i” as your variable when writing FOR loops)
x < 25 is the boolean test
x++ is the increment
This says, start at 0 and count to 25 in increments of 1.
Remember, x++ is a shorthand way of writing x = x + 1
The same goes for x– (x = x – 1)
For loops are handy because unlike the while loop, you don’t need to reset your x variable at the top of the draw loop. You’re using a local variable that is reset when it’s declared inside of the for loop (it’s like making a new variable everytime we loop through draw).