Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Jul 23, 1998

Static Variables

Static variables (not to be confused with static class members) have the qualities of both global and local variables: they are initialized by default to binary zeroes (unless explicitly initialized with a different value); they are created before program's outset and destroyed after program's termination. But like local variables, they are accessible only from within the scope in which they are declared. These properties make static variables ideal for storing a function's state on recurrent invocations since they reserve their values from the previous call. For example:
 
void MoveTo(int OffsetFromCurrentX, int OffsetFromCurrentY)
{
static int currX, currY; //currX and currY have a zero value when MoveTo is invoked for the first time
currX += OffsetFromCurrentX; //set new x position; new value will persist when MoveTo is called again
currY += OffsetFromCurrentY; //set new y position; new value will persist when MoveTo is called again
PutPixel(currX, currY); //draw in new position
return;
} 
void DrawLine(int x, int y, int length)
{
for (int i=0; i<length; i++)
   MoveTo(x++, y--); //on each invocation, MoveTo has access to the previous values of currX and currY  
}
C++ users should note, however, that when the need arises for storing a function's state, a better design choice would be to use a class, in which data members can replace the static variables and a member function replaces the global function.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date