Sunday, May 29, 2011

Static variable in C/C++

Thanks to the iPhone development platform, the C++ once again gets the notice of mobile developers. This post talks few issues about static keyword in c/c++.

1. Using static for variable in file scope
If the same named variable is defined in multiple files, compiler will report an error due to the duplicated definition. Adding static for the variable definition will make the variable's scope to the current file, so that they will not conflict with each other. Note, the static variable defined in each file has its own instance. Changing the static variable's value in one file will not affect another file's variable value.
If you want to share the same instance, using extern keywork.

2. Using static for variable in class scope
This is quite easy to understanding, since it is similar to .net or java. The variable belongs to the class instead of a particular class instance.

3. Using static for variable in method scope
The variable will be initialized once, and each time when the mothod gets called, the same instance will be used. It is more useful in c, as in c++, we can just define a class member to do the same thing.

In all cases, if adding const in the definition, then the variable can not be updated once it is initialized.

Jonathan