What is the difference between initializing a variable inside/outside setup() ?

edited October 10 in Programming Questions

Hey!

Is there a difference between initializing a variable inside / outside setup?

Such as this:

int x;

setup() {
x = 5;
}

and this:

int x = 5;

setup() {
}

Thanks in advance!

Answers

  • edited October 10 Answer ✓
    • When we run a sketch, all of its ".pde" files are concatenated as 1 valid ".java" file.
    • And then it is compiled and run.
    • The whole sketch is wrapped up as 1 Java subclass which extends Processing's PApplet class.
    • All "global" variables become fields of that subclass.
    • And likewise, all functions become methods of that subclass.
    • Initializing fields at the same time they're declared happens even before a class' constructor is run.
    • Method setup() is called back much later.
    • It is safer to initialize fields within setup() b/c there are some PApplet fields, like width and sketchPath, which aren't initialized yet at field declaration time.
    • However, if our fields don't depend on those few PApplet "delayed" fields, we can initialize them before setup().
Sign In or Register to comment.