CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

static declaration question

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
s_mack



Joined: 04 Jun 2009
Posts: 107

View user's profile Send private message

static declaration question
PostPosted: Thu Sep 17, 2009 6:52 pm     Reply with quote

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

View user's profile Send private message

PostPosted: Thu Sep 17, 2009 7:57 pm     Reply with quote

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

View user's profile Send private message

PostPosted: Thu Sep 17, 2009 10:34 pm     Reply with quote

I thought the initialization of it made it zero, but that's only for static. Thanks for correcting/informing me.
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group