I’m programming something with an Arduino, which I believe uses C as the base language. I have this loop:
int i = 0;
void loop()
{
//Set The output pin to the MIDI note number - 60.
int pinNumber = noteNumber - 60;
if (midiMessage == 144) {
if (velocity == Triggered) {
registerWrite(pinNumber, HIGH);
i = pinNumber;
}
}
if (midiMessage == 128) {
if ((i % 8) == (pinNumber % 8)) {
if (velocity == Stopped) {
registerWrite(pinNumber, LOW);
}
}
}
}
I know the above code doesn’t work right, but what I’m trying to do is assign the i variable if the first condition is met if (velocity == Triggered), and then be able to use it when the midiMessage == 128 condition is met.
iis a global variable, meaning that it’s initialised to 0 (explicitly) when your program starts, and then can be changed by any code that can see it.So, if your question is:
(and it seems to be, based on the comments you left in the question) then the answer is yes.
In other words, when you enter
loop()withmidiMessageequal to 144, it will setitopinNumber(noteNumber - 60).Then the next time you enter
loop()withmidiMessageequal to 128, it will use the currenti(whatever it was last set to).Of course, if you enter
loop()withmidiMessageequal to 128 before you call it whenmidiMessageequals 144, the value ofiwill be zero.If that declaration of
iwas inside theloop()function, then it would be re-initialised each time the function was called, but that’s not the case here.Of course, good programming practice would suggest that you should put it inside the function if that’s the only place you use it (this may not be the case).
This restricts its “visibility” (a) to that function so that there’s no chance other code may use it inadvertently (this is especially a problem for a variable called
i– you may want to think of a better name for it).To restrict its visibility like that while still allowing it to exist between function calls, you would use something like:
This still initialises it once, at program startup (even though it’s inside the function) and keeps its value in between different invocations of
loop(). It also stops code from outside of that function from “seeing” the variable.(a) Note that “visibility” as used here is not the term the ISO standard uses. I use that term for my introductory coding classes since “visibility” is easier understood than “scope”.