Go Down

Topic: declaring variables in the loop? (a variable scope question) (Read 3 times) previous topic - next topic

neurascenic

Nick,

Thanks for the reply;  What happens if I declare the variable in the Loop()  but don't set the value in the declaration?
is the variable the same (i.e. the same address)  or is it a new variable each time the loop such as is the case with recursion?  Or does the value remain from the last iteration?

I am used to dealing with the primary function being the main()  which doesn't loop.  It is perfectly fair to declare variables there.

Thanks,

Chris

Nick Gammon

If you don't set the value it is undefined basically. Maybe it will be the same, I wouldn't rely on it.

You don't have to use "loop" - just never exit "setup".

Anyway, another approach is to use static, eg.

Code: [Select]
void loop ()
  {
  static int nomnom = 0;

  nomnom++;  // adds 1 each time
  }


The static variable has local scope but global lifetime, if you see what I mean.



neurascenic

Static!!!  Perfect!!!  I do see!

That is exactly what I want!

Thank you oh so very much!

Chris

Go Up