Local Variable Error

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

loop() is a function. As soon as you exit a function all of its local variables, in your case areaLast, disappear.
The random value of 544 is because areaLast is allocated, but not initialized, on the stack.
After the first time through the loop function, areaFlag will always be zero so you don't set areaLast to AreaNum and areaLast will have whatever arbitrary value happened to be on the stack at that point.

Pete

I got the part I was missing. When it hits the end of the loop function, it leaves the function, all the local variables are destroyed. I wasn't thinking it left the function. But it makes sense, "void loop()" works like any other function.

Thanks!

Dave