Go Down

Topic: static variables (Read 3709 times) previous topic - next topic


I just learned about defining static variables.
If a variable is only used in my loop() routine, should I use
static int myVar;

or just
int myVar;

...since the loop() routine will always be running, even if I go to other functions.


If you need to retain the information in that variable between multiple loops, make it static. Otherwise, don't.


To elaborate on WizenedEE's correct reply if you make the variable static it's value will be retained when the function is exited so when you call the function again it will have the value it had previously. If you don't make it static then the memory space required to hold that variable is made available when the function exits. So the cost of a static variable is memory space. statics have their place but shouldn't be used unless necessary.


...I need the variable to retain it's value always.  So even though it's in the loop() routine, as so as I go to another function, it'll be lost.  Correct?  So it needs to be static.

Morris Dovey

Not quite. If you call another function from within loop(), all of loop()'s variables (both automatic and static) will be preserved through the call.

If you exit loop() either with an explicit return or by "falling off the end", only the static variables will be preserved.
There's always a better way!

Professor Chaos

Of course you could use a global variable as well.


...since the loop() routine will always be running, even if I go to other functions.

"always be running" might be a bit misleading you:
Sure you may call other functions from loop, and after returning from there, your code executes just the next line.
But loop() ends at the bottom (or with a return; statement), it is just (rather soon) restarted again, and all local non-static variables are created from fresh.

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131