09.04.2016 Views

www.ebook777.com

Make_Getting_Started_with_Processing_Second_Edition

Make_Getting_Started_with_Processing_Second_Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

D/Variable Scope<br />

The rule of variable scope is defined simply: a variable created<br />

inside a block (code enclosed within braces: { and }) exists only<br />

inside that block. This means that a variable created inside<br />

setup() can be used only within the setup() block, and likewise,<br />

a variable declared inside draw() can be used only inside the<br />

draw() block. The exception to this rule is a variable declared<br />

outside of setup() and draw(). These variables can be used in<br />

both setup() and draw() (or inside any other function that you<br />

create). Think of the area outside of setup() and draw() as an<br />

implied code block. We call these variables global variables,<br />

because they can be used anywhere within the program. We call<br />

a variable that is used only within a single block a local variable.<br />

Following are a couple of code examples that further explain the<br />

concept. First:<br />

int i = 12; // Declare global variable i and assign 12<br />

void setup() {<br />

size(480, 320);<br />

int i = 24; // Declare local variable i and assign 24<br />

println(i); // Prints 24 to the Console<br />

}<br />

void draw() {<br />

println(i); // Prints 12 to the Console<br />

}<br />

And second:<br />

void setup() {<br />

size(480, 320);<br />

int i = 24; // Declare local variable i and assign 24<br />

}<br />

void draw() {<br />

println(i); // ERROR! The variable i is local to setup()<br />

}<br />

211

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!