Is there any difference between a variable declared as static
outside any function between C and C++. I read that static
means file scope and the variables will not be accessible outside the file. I also read that in C, global variables are static
. So does that mean that global variables in C can not be accessed in another file?
The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).
static variable is used for a common value which is shared by all the methods and its scope is till the lifetime of whole program. In the C programming language, static is used with global variables and functions to set their scope to the containing file.
Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.
A global variable can be accessed from anywhere inside the program while a static variable only has a block scope. So, the benefit of using a static variable as a global variable is that it can be accessed from anywhere inside the program since it is declared globally.
No, there's no difference between C and C++ in this respect.
Read this SO answer about what static
means in a C program. In C++ there are a couple of other meanings related to the use of static
for class variables (instead of instance variables).
Regarding global vars being static
- only from the point of view of memory allocation (they are allocated on the data segment, as all globals are). From the point of view of visibility:
static int var; // can't be seen from outside files
int var; // can be seen from outside files (no 'static')
There are two concepts here "static linkage (or scope)" and static allocation".
Outside a function the keyword refers to linkage, inside it refers to allocation. All variables outside a function have static allocation implicitly. An unfortunate design perhaps, but there it is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With