It’s not rare, but it definitely depends on the use case. I’m assuming you’re new to C++/openFrameworks so I don’t want to confuse you at the outset and understanding when to use what will come with practise and more experience.
One of the most common ways to use local variables is to do some quick math to keep things legible. Imagine you have two global variables, input1
and input2
, both in the range of 0-100. Now you want to use the average of the two to set the radius of a circle. One of the ways to do it would be to do ofDrawCircle(x, y, (input1 + input2)/2);
Now, this is a simple case, but imagine more complex mathematics. You could easily break it down into,
int radius = (input1 + input2)/2;
ofDrawCircle(x, y, radius);
or even break it down more to,
int total = input1 + input2;
int average = total/2;
ofDrawCircle(x, y, average);
Now imagine you wanted to draw the circle within the range of 0 -7365. You’d want to use the ofMap
function using the average and it can get really ugly really soon doing ofDrawCircle(x, y, ofMap((input1 + input2)/2, 0, 100, 0, 7365));
where if you had the local variable radius or average, it would be a much nicer and readable bit of code
//case 1:
int radius = (input1 + input2)/2;
int drawRadius = ofMap(radius, 0, 100, 0, 7365);
ofDrawCircle(x, y, drawRadius);
//case 2:
int total = input1 + input2;
int average = total/2;
int drawRadius = ofMap(average, 0, 100, 0, 7365);
ofDrawCircle(x, y, drawRadius);
In these above cases, your variables would not be required outside of this scope, so it would be the perfect time to use them. There are some other use cases for local variables as well, but as I said earlier, I don’t want to confuse you in case you’re a beginner and this would probably be one of the simplest ways of using local variables when starting out.