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 › Proper syntax for declaring global variables
Page Index Toggle Pages: 1
Proper syntax for declaring global variables? (Read 451 times)
Proper syntax for declaring global variables?
Jan 31st, 2008, 12:19am
 
Good evening, all.  I'm new to Processing and new to these boards, so forgive me if this has been covered before.  (I searched, so I don't think it has.)

I am not sure if this is a syntax question or a bug.  For whatever reason, Processing will not let me set a variable value (without declaring it at the same time) before setup().  For example, this works fine:

Code:
int varName;
int otherVarName = 100;


But this does not:

Code:
int varName;
varName = 100;


This latter example triggers an "unexpected token: void" error once the compiler hits setup().

For reasons of code cleanliness and personal style, I may prefer to declare my variables first, and then assign them values later.  But it looks like Processing will only let me either (A) just declare them, and assign values later (like within draw()), or (B) declare and assign value in one statement.

Any thoughts?  Is this a syntactical issue?  Thanks in advance.
Re: Proper syntax for declaring global variables?
Reply #1 - Jan 31st, 2008, 9:12am
 
The right way will be declaring the  variables before setup to make them global and assign the values in the setup method. From a coding style view I'm will only assigned a value to constants when they will be declared.

Code:


int myGlobal;
float MYCONSTANT = 3.41;

void setup(){
myGlobal = 1;
String myLocal="local";
}

Re: Proper syntax for declaring global variables?
Reply #2 - Jan 31st, 2008, 2:14pm
 
Thanks, Andreas.  That sounds like a good approach, although I'm still curious about why Processing won't let me assign variable values before setup().
Re: Proper syntax for declaring global variables?
Reply #3 - Jan 31st, 2008, 5:06pm
 
The 'global variable' you declare before setup is actually a field of your main class (which is hidden by Processing).

In Java, you can only assign a value to a variable :
1) in a method, or
2) when you declare it : it is a kind of shortcut so the variable will be set at this value in the constructor.
Re: Proper syntax for declaring global variables?
Reply #4 - Jan 31st, 2008, 7:23pm
 
Thanks, antiplastik.  I am new to Java as well, so that explanation is very helpful.
Page Index Toggle Pages: 1