GordeyChernyy / DrawingTool

Brushes, Live drawing, Kaleidoscope, Moving frames
1 stars 0 forks source link

Local and Global variables in C++ #5

Closed GordeyChernyy closed 8 years ago

GordeyChernyy commented 8 years ago

Hey @stevelackermann, @anirudh-eka I have question about variables in C++. I have a global variable:

vector<char> letters;

Then I have a local variable inside method with the same name letters:

void breakIntoLetters (string data, vector<char> *letters){
    for (int i = 0; i < data.length(); i++) {
        char &c = data.at(i);
        letters->push_back(c);
    }
}

Seems like this local variable don't affect global variable, which what I need to make code more cleaner. Is there any traps using this technics?

ghost commented 8 years ago

It's frowned upon because it can cause confusion on the part of people reading your code, but it won't cause any problems other than that. And I'd say that if it makes sense to use the same name twice, go ahead and do it.

Oftentimes people will name global variables following a convention like prepending g to the name, so letters would become gLetters. That avoids name collisions, but it's a stylistic choice up to the programmer.

In c++, if you want to reference the global in breakIntoLetters, you can do ::letters , like in the example below:

ofImage myImage;

void myfunc(ofPixels *myImage) { myImage->getPixels(); ///the argument passed to the function ::myImage.setImageType(OF_IMAGE_COLOR_ALPHA); /// the global }

GordeyChernyy commented 8 years ago

That makes sense! Thanks!