The Arduino reference says:
"The static keyword is used to create variables that are visible to only one function. However unlike local variables that get created and destroyed every time a function is called, static variables persist beyond the function call, preserving their data between function calls.
Variables declared as static will only be created and initialized the first time a function is called."
I understand that a static variable is initialized only once, when the function is called for the first time, and that its data will be preserved between function calls. So, why this does'nt work??
void setup() {
Serial.begin(9600);
}
void loop() {
printOneTime();
}
void printOneTime() {
static int done;
if (done == 0) {
Serial.println("Printed one time");
done = 1;
}
}
You have created an uninitialized local variable. When you declare a global variable the variable is automatically set to a value of 0 if not given an initial value. Not so a static local variable. It will take on the value of whatever was in the memory location that gets assigned to the variable.
Read the forum guidelines to see how to properly post code and some information on how to get the most from this forum. Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.
OK, I get it. I was assuming that an uninitialized static local variable and uninitialized local variable were the same as far as their initial value. I was wrong.
Here is a sample of what I found while looking for an answer:
It depends on the storage duration of the variable. A variable with static storage duration is always implicitly initialized with zero.
As for automatic (local) variables, an uninitialized variable has indeterminate value. Indeterminate value, among other things, mean that whatever "value" you might "see" in that variable is not only unpredictable, it is not even guaranteed to be stable. For example, in practice (i.e. ignoring the UB for a second) this code