Jump to content

Static variable

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 86.61.232.26 (talk) at 20:55, 26 April 2009 (→‎intro: (+) blocks, (+) simplified, needs term checking). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, a static variable acts as global variable and is visible only in "its" function (or object). The data / value of a static variable persists for the life of the running process.

Typically, a static variable has a broader scope than other variables.

The values of static variables may be set once (at run-time) or may be changed multiple times during program execution.

C (programming language) "introduced" and popularized the term static variable, nevertheless it is also used in many derived programming languages. In languages with different heritage, the same concept may instead be called global variables.

For constants

Computer programs may store constants in constant variables or in static variables, depending on the available features of the programming language. For example, a program that uses an approximation of pi might be easier to write, read, and maintain with a variable called "PI" instead of multiple occurrences of "3.14159"

C Example

#include <stdio.h>

/* Function prototypes */
void test1(void);
void test2(void);

void main()
{
   printf("\n\t A static variable persists for the life of the running process (program).");
   printf("\n\t Static vars are the same as a global var.");
   printf("\n\n\t A non-static (automatic) variable looses it's value as soon as you");
   printf("\n\t leave a function.\n");
 
   int i = 0;

   for( i = 1; i < 5; i++ )
   {
   printf("\n\n\t Function call %d", i);
     test1();
     test2();
   printf("\n");
   }

   printf("\n\n\t Press <Enter> key to exit... ");
   while ((getchar()) != '\n'); printf("\n\n");

 }

void test1(void) /* Function test1 with an automatic variable */
{
   int count = 0;
   printf("\n\t test1   count = %d (auto)", ++count );
} 


void test2(void) /* Function test2 with a static variable */
{
   static int count = 0;
   printf("\n\t test2   count = %d (static)", ++count );
}

For scope

In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

For local variables

Most programming languages include the feature of subroutines. Variables local to subroutines (local variables) are usually created and destroyed within the subroutine itself (so-called automatic variables). Some languages, however, (e.g., the C programming language) allow subroutines to retain the value of variables between calls, so that the function can preserve its state if necessary. For example, a static variable can record the number of times its subroutine has been executed. Doing so is otherwise possible using global variables or external storage, like a file on disk. Additionally, it limits the compiler scope of the variable in question strictly to that function, even as the space allocated is in the static area.

For class variables

Object-oriented programming languages use classes and objects. In this case, a class variable means a variable that is not associated with instances of the class. There is exactly one copy of the variable that is shared among methods of all instances no matter how many or how few instances exist. In C++, class variables are known as static data members.

C# Example

public class Request
{
	private static int count;
	private string url;

	public Request()
	{
		//Create a new instance of Request
		//Count all requests
		Request.count++;
	}

	public string Url
	{
		get
		{
			return this.url;
		}
		set
		{
			this.url = value;
		}
	}

	public static int Count
	{
		get
		{
			//Do not use the this keyword here
			//as this refers to "THIS INSTANCE"

			return Request.count;
		}
		//Do not allow the developer to SET this value
	}
}

C++ Example

class Request
{
	private:
		static int count;
		string url;
	
	public:
		Request() { count++; }
		string getUrl() const { return url; }
		void setUrl(string value) { url = value; }
		static int getCount() { return count; }
};
int Request::count = 0;

In this sample, count applies to the class while url applies to each instance. Note that the count variable must be initialized outside the class.

References

http://ee.hawaii.edu/~tep/EE160/Book/chap14/subsection2.1.1.6.html

See also