Junior — Middle
How does the use of the static keyword affect the properties of global variables in a program?
sobes.tech AI
Answer from AI
The keyword static when declaring a global variable in C/C++ limits the scope of that variable to the current file (translation unit). This means that such a variable will not be visible or accessible from other files, even if they include this file via extern.
Thus, static makes a global variable internal to the file, preventing name conflicts and providing encapsulation at the file level.
Example:
// file1.c
static int counter = 0; // visible only in file1.c
void increment() {
counter++;
}
// file2.c
extern int counter; // Error: counter is not visible due to static