View previous topic :: View next topic |
Author |
Message |
s_mack
Joined: 04 Jun 2009 Posts: 107
|
static declaration question |
Posted: Thu Sep 17, 2009 6:52 pm |
|
|
I'm confused about the behavior of my program as it relates to static variables.
A common definition of "static": Quote: | In C , a variable declared as static is local to a particular function. It is initialised once and on leaving the function, the static variable retains the value. Next time when the function is called again, the static variable already has the value from the previous function call. |
Got it. To me that implies that a non-static variable would then lose its value between function calls, right?
Take this simple example:
Code: | int16 test( int16 bar )
{
static signed int16 foo;
foo += bar;
return foo;
}
void main (void)
{
printf( "%Ld\n", test( 10 ) );
printf( "%Ld\n", test( 10 ) );
while(1)
{
}
} |
I would expect that to print 10, then 20. And it does. Now remove "static" and I would expect it to print 10 then 10 but it does not... it still prints 10 then 20.
Why is the value retained between function calls? Is this expected?
Thanks. |
|
|
SherpaDoug
Joined: 07 Sep 2003 Posts: 1640 Location: Cape Cod Mass USA
|
|
Posted: Thu Sep 17, 2009 7:57 pm |
|
|
A non-static variable is not guaranteed to retain it's value between calls, but it might, or it could be a random number. You just happen to be lucky that that RAM location has not been re-used yet. There is certainly no reason to expect it would be zero. _________________ The search for better is endless. Instead simply find very good and get the job done. |
|
|
s_mack
Joined: 04 Jun 2009 Posts: 107
|
|
Posted: Thu Sep 17, 2009 10:34 pm |
|
|
I thought the initialization of it made it zero, but that's only for static. Thanks for correcting/informing me. |
|
|
|