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.

See also  Small Business Strategies with Venmo

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist