Difference between revisions of "Meaning of Static"
(Created page with "The '''static''' variable has so many meanings that it is best to describe them by example: === static in Header File === '''Every file''' that includes '''my_file.h''' will ...") |
(No difference)
|
Latest revision as of 18:08, 17 April 2013
The static variable has so many meanings that it is best to describe them by example:
Contents
static in Header File
Every file that includes my_file.h will receive its own, independent copy of my_var and my_arr[128]. This copy is not shared between two files that include my_file.h. Use this strategy to create multiple copies of these variables at compile time, but avoid it in general because it is a big mess to maintain.
/* my_file.h */
static int my_var = 1;
static int my_arr[128] = { 0 };
static in Source File
When static functions or variables are defined in a source file, then these are inaccessible members for anyone else, and thus private members for this source code file. No one else can access them and other source file can have their own static members with the same name and there will not be any compiler issue. If you declare multiple hello_world() functions in multiple source files without the static keyword, then you will get compiler error for multiple definitions of the same function.
/* my_file.c */
static int my_var = 0;
static void hello_world(void)
{
/* Your code */
}
static inside Functions
Static members of a function are like global variables, except that they are private to the function. They are global in a sense that they are not re-declared each time the function is called. The static variables are declared and initialized once, and their value is preserved across multiple function calls. In the example below, we will see i = 1 and i = 2 and so forth each time the function is called.
void hello_world(void)
{
static int i = 0;
i++;
printf("i = %i\n", i);
}
void init_once(void)
{
// This will only occur once.
static int *my_var_ptr = malloc(sizeof(int));
}
static inside Classes
In C++, the static member is shared between ALL instances of the class. They may be tricky to access because each class doesn't have its own variable and therefore is inaccessible by this-> pointer. The static variable must be declared outside of the class scope in the source file. The second case is a static variable inside of a function. This static variable is again shared between ALL instances of the class.
class foo
{
public:
foo() { ++num_instances; }
void hello(void)
{
/* i is shared between all instances, therefore each time hello()
* is called, even from multiple instances, it increments a single
* variable i
*/
static int i = 0;
i++;
}
private:
static int num_instances;
}