Static Variables

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 timecurrX += OffsetFromCurrentX; //set new x position; new value will persist when MoveTo is called againcurrY += OffsetFromCurrentY; //set new y position; new value will persist when MoveTo is called againPutPixel(currX, currY); //draw in new positionreturn;} void DrawLine(int x, int y, int length){for (int i=0; i

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.


Share the Post: