Question about Global and Local Variables
in
Programming Questions
•
2 months ago
Hi, I am relatively new to programming, and I am learning through the book
Learning Processing as well as experimenting and building stuff independently. I have a question for experienced programmers regarding variables and passing copies. My question is "Is it necessary for variables that pass as copies to be made global?"
Here is a concrete example of my problem:
int carX = width-100;
int carY = height-450;
int carLength = width/10;
int carWidth = height/20;
int wheel = carLength/4;
void setup () {
size (800, 800);
background (0, 100, 50);
}
void draw () {
road ();
carLooks (700, 350, 80, 40, 20, color (random(255), random(255), random(255)));
carLooks (450, 350, 80, 40, 20, color (random(255), random(255), random(255)));
carLooks (200, 350, 80, 40, 20, color (random(255), random(255), random(255)));
}
void road () {
int roadX = 400;
int roadY = 400;
strokeWeight (5);
stroke (255);
fill (128);
rectMode (CENTER);
rect (roadX, roadY, width+5, height/4);
// Lane dividing lines
for (int i = 0; i <= width; i += 96) {
line (i, roadY, i+48, roadY);
}
}
void carLooks (int carX, int carY, int carLength, int carWidth, int wheel, color c) {
// Car body
noStroke ();
fill (c);
rect (carX, carY, carLength, carWidth, 50);
noLoop ();
// Car wheels
fill (0);
rect (carX-wheel, carY-wheel, wheel, wheel/2, 5);
rect (carX+wheel, carY-wheel, wheel, wheel/2, 5);
rect (carX-wheel, carY+wheel, wheel, wheel/2, 5);
rect (carX+wheel, carY+wheel, wheel, wheel/2, 5);
}
I have tried to put the global variables (bold) in the block of code entitled "void carLooks" but I received an error message reading "duplicate local variable carX...". Is there a way to move the bold section to "void carLooks" without receiving this error message? It seems reasonable that this may not be possible, that these variables must remain global because the variables are being used in a block of code outside of "void carLooks", namely, "void draw", but I don't have a firm understanding on how passing copies works. The reason I would like to turn the global variables into local ones under "draw carLooks" is because I don't see myself reusing them in other blocks of code, and I am practicing how to be organized by keeping variables local whenever possible. If there is a way, then let me know how or refer me to a source, and if there is not, then that is okay too.
Thank you all for your time.
Twitter: @eselotter
*edit*
It is also worth mentioning that the reason I am passing the copies of the parameters to "void draw" is so I can create multiple versions of the car. This is why I am avoiding using carLooks (); without parameters.
1