In C and C++, the keyword static exists, but its usage and meaning have some differences. Below are some main differences in the use of static in C and C++:
1. Storage Duration of Local Variables
-
C Language: When
staticis used for local variables in C, it primarily changes the storage duration to a static lifetime. This means the variable persists for the entire duration of the program, rather than being destroyed when its scope ends. The variable is initialized the first time the function is called, and its value persists across subsequent function calls, maintaining state from previous invocations.Example:
cvoid function() { static int count = 0; count++; printf("count is %d\n", count); } -
C++: Similarly, static local variables are used in C++, but C++ introduces the concept of classes, which extends the usage of the
statickeyword.
2. Static Members of Classes
-
C++: An important extension in C++ is allowing the use of the
statickeyword within classes. Static member variables belong to the class itself, not to individual instances. This means that regardless of how many objects are created, static member variables have only one copy. Static member functions are similar; they do not depend on class instances.Example:
cppclass Example { public: static int staticValue; static void staticFunction() { std::cout << "Accessing static function." << std::endl; } }; int Example::staticValue = 5; // Call Example::staticFunction(); std::cout << Example::staticValue << std::endl;
3. Linkage
-
C Language: In C,
staticis used to hide global variables and functions, making them visible only within the file where they are defined, rather than throughout the entire program. This is beneficial for encapsulation and preventing naming conflicts.Example:
cstatic int hiddenVariable = 50; static void hiddenFunction() { // Visible only within this file } -
C++: In C++,
staticcan also be used to define file-private global variables and functions, with usage similar to C.
Summary
Although the basic concept of static in C and C++ is similar—both are used to declare variables with static storage duration or to restrict the scope of variables and functions—C++ extends the usage of static to a broader context, particularly within classes, introducing static member variables and static member functions. These provide class-level scope rather than instance-level scope for data and functions.