Using local variables in "Loop"

Is it wrong to use local variables in "loop" ?

 void loop
{
  int testThis = 23;
  {
      ++testThis;
     // Stuff in here
  }
}

This looks like a case waiting for a Stack-Overflow. OR, are all local variables disposed of at the end of each iteration of loop?

Thanks

loop is just like every other function. The locals are destroyed when the function exits.

Look in your folder where you installed the IDE and find main.cpp. From that file you will see that loop is just a regular function like any other you may write.

Is it wrong to use local variables in "loop" ?

No. If you want them to retain their value between iterations of loop() even if is changed then declare them static. They will be initialised with the value given and if changed in loop() they will not be reinitialised. If you don't declare them static then they will be reinitialised each time through loop(). Try this

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  static int staticInt = 0;
  int nonStaticInt = 0;
  Serial.print("static : ");
  Serial.println(staticInt);
  Serial.print("non static : ");
  Serial.println(nonStaticInt);
  staticInt++;
  nonStaticInt++;
  delay(1000);
}

Thanks everyone, especially Helicopter Bob, I didn’t realize that loop is called every time. I assumed {gasp} that it stayed within itself.

Pascal for 30+ years and I am on a steep learning curve here. :slight_smile: