We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Noob question about initializing variables
Page Index Toggle Pages: 1
Noob question about initializing variables (Read 250 times)
Noob question about initializing variables
Mar 2nd, 2009, 7:08pm
 
Quote:
int[] x = new int[100];
int count;

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

void draw() {
 x[count] = mouseX;
 count++;
 if (count == x.length) {
   x = expand(x);
   println(x.length);
 }
}



Hello, I was working on the preceding example and noticed that the variable "count" is declared but no value is assigned to it, yet the program still works fine. So if no value is specifically assigned to a variable, is it automatically set to zero?

I apologize if I've used any terminology incorrectly.
Re: Noob question about initializing variables
Reply #1 - Mar 2nd, 2009, 7:38pm
 
The primitive types, float, int, boolean, byte etc all have default values. Object types however need to be explicitly initialised.
Re: Noob question about initializing variables
Reply #2 - Mar 2nd, 2009, 7:43pm
 
Thank you!
Re: Noob question about initializing variables
Reply #3 - Mar 2nd, 2009, 10:46pm
 
You have to distinguish variables local to a function (method) and at class level (or "global" at Processing sketch level).

Local variables doesn't have a default value: Java compiler will complain if you use them before setting them.

Class level variables (or fields, or members) always have a default value: 0 or 0.0 for numbers, false for booleans, null for objects, etc.

So there is no need to set these variables to default values, it is even seen as bad practice (as it is redundant: they will be initialized twice).
But of course, you can set them to another value at declaration time (although most objects should be init in setup(), because at this time you know stuff like data folder path, width and height, etc.).
Re: Noob question about initializing variables
Reply #4 - Mar 2nd, 2009, 11:05pm
 
PhiLho  wrote on Mar 2nd, 2009, 10:46pm:
Note to what JohnG added: what he wrote is correct for local variables, and Java compiler will complain if you don't initialize objects. It is still true for member variables (ie. fields, variables declared at class level) except that objects there are always initialized at null. So there is no need to set these variables to default values,it is even seen as bad practice.


Cool thanks! Very useful info.
Re: Noob question about initializing variables
Reply #5 - Mar 3rd, 2009, 6:10pm
 
Argh! Actually the info you quote is incorrect... Sad
I edited my message to give better information!
Page Index Toggle Pages: 1