Pages: [1]   Go Down
Author Topic: static variables  (Read 2522 times)
0 Members and 1 Guest are viewing this topic.
South East USA
Offline Offline
God Member
*****
Karma: 5
Posts: 658
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Offline Offline
Edison Member
*
Karma: 19
Posts: 1041
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

0
Offline Offline
Sr. Member
****
Karma: 4
Posts: 329
KC4MM
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

South East USA
Offline Offline
God Member
*****
Karma: 5
Posts: 658
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

...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.
Thanks
Logged

West Des Moines, Iowa USA
Offline Offline
Sr. Member
****
Karma: 2
Posts: 428
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

There's always a better way!

0
Offline Offline
Full Member
***
Karma: 1
Posts: 225
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Of course you could use a global variable as well.
Logged

Germany
Offline Offline
Faraday Member
**
Karma: 59
Posts: 3091
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

...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.
Logged

Pages: [1]   Go Up
Jump to: