Junior — Middle
What is the difference in the use of the keyword static in C and C++ languages?
sobes.tech AI
Answer from AI
In the C language, the keyword static is used to modify the scope and lifetime of variables and functions:
- For global variables and functions,
staticlimits their scope to the current file (internal linkage), meaning they are not visible from other files. - For local variables within a function,
staticpreserves the variable's value between function calls (the variable lives for the duration of the program).
In C++, static retains these meanings but also adds usage in the context of classes:
- In a class,
staticvariables and methods belong to the class itself rather than to any specific object. Such members exist as a single instance for the entire class.
Example:
// C and C++
static int counter = 0; // visible only in this file
void func() {
static int callCount = 0; // preserves value between calls
callCount++;
}
// In C++
class MyClass {
public:
static int staticValue; // shared among all objects
static void staticMethod() {
// ...
}
};
int MyClass::staticValue = 0;
Thus, the main difference is that in C++, static is also used to define static class members, which is not present in C.