I had a problem in a sketch where a local variable was not giving the expected result. The sketch is over 1600 lines long, so I created a new sketch to try to replicate the problem so I could find a solution. I replicated the problem in the sketch below and I found a solution, but I thought I would share this, and see if anyone knows why this caused a strange result.
Here is the sketch:
int areaFlag = 1;
int areaNum = 1;
void setup() {
Serial.begin(115200);
}
void loop() {
int areaLast; // Comment this line out, and
//static int areaLast = 0; // uncomment this and it works correctly
if (areaFlag) areaLast=areaNum;
Serial.print(areaNum);
Serial.print(" ");
Serial.print(areaLast);
Serial.print(" ");
Serial.println(areaFlag);
areaFlag = 0;
areaNum = areaNum + 1;
if (areaNum > 3) areaNum=0;
if (areaNum == areaLast) areaFlag=1;
delay(1000);
}
The expected result was:
areaNum should be: 1, 2, 3, 0, 1, 2 .... repeating
areaFlag should be 0 unless areaNum and areaLast are both 1
local variable areaLast should always be 1 in this example.
The actual result was ok in the first pass through the loop areaNum=1, areaLast=1, areaFlag=1.
but the next pass through the loop, areaLast=544 ? (<==edit)
In the first line of the loop, I added a "static" qualifier and the code produced the expected results.
Does anyone know why the areaLast variable resulted with this unexpected number? I understand the local variables are destroyed every time the function is called. I thought the local variable should be retained as long as your in the same function or loop. It appears that the local variable was re-initialized in the second pass of the loop, and the 544 value is just some random remains from a register.
Thanks,
Dave