Loading...
Logo
Processing Forum
Here is another basic question about variables.
 
I know you have the option of defining then either inside of functions or outside.  Outside means that they are available within all of the functions and inside means they only work inside that specific function.  Also if they are defined in a specific command like a for loop, they only are accessible within that loop.
 
My question is why.  Why would you not just make them all available all the time?
 
Is there a drwback such as reduced speed, memory consumption, etc or is it just an option for the purpose of organization??
 
I have been defining everything up front just to have a place where my whole variable list is placed but I don't know if I am hurting myself in the process... specially in arduino sketches where speed and memory are big issues.

Replies(1)

You are talking about variable scope.  Local scope vs global scope. You asked why we don't just have everything default to global scope.  Some older programming languages do this, especially ones intended for teaching, such as BASIC.  

Local scope does indeed reduce memory consumption.  By communicating that a variable is only going to be used locally, it can be stored In a register or in the local stack frame, or it can be marked for later garbage collection.

More importantly, local scope reduces the chance of name collisions.  If everything were global scope, and you started using libraries, you would run the risk that every variable you name has already been used, unbeknownst to you, in some library code.  You would be overwriting those variables, and accidentally introducing bugs.  Local scope reduces the risk of this kind of problem. 

The Java programming language that Processing is a derivative of is also used for larger, more complex projects which are worked on by more than one person.  Sometimes sizable teams.  In these projects, name collision is more of an issue.

Having said that, there is nothing wrong with using global variables in your projects.  There are some programmers who, in my opinion, go overboard in removing every global variable from their projects. For most Processing projects, this is overkill.