A variable declared globally is said to having program scope
A variable declared globally with static keyword is said to have file scope.
For example:
int x = 0; // **program scope** static int y = 0; // **file scope** static float z = 0.0; // **file scope** int main() { int i; /* block scope */ /* . . . */ return 0; }
What is the difference between these two?
File Scope: These variables are usually declared outside of all of the functions and blocks, at the top of the program and can be accessed from any portion of the program. These are also called the global scope variables as they can be globally accessed.
Scope is a concept that refers to where values and functions can be accessed. Various scopes include: Global scope (a value/function in the global scope can be used anywhere in the entire program) File or module scope (the value/function can only be accessed from within the file)
There are mainly two types of variable scopes: Local Variables. Global Variables.
A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable it cannot be accessed. There are three places where variables can be declared in C programming language − Inside a function or a block which is called local variables.
Variables declared as static
cannot be directly accessed from other files. On the contrary, non-static
ones can be accessed from other files if declared as extern
in those other files.
Example:
foo.c
int foodata; static int foodata_private; void foo() { foodata = 1; foodata_private = 2; }
foo.h
void foo();
main.c
#include "foo.h" #include <stdio.h> int main() { extern int foodata; /* OK */ extern int foodata_private; /* error, won't compile */ foo(); printf("%d\n", foodata); /* OK */ return 0; }
Generally, one should avoid global variables. However, in real-world applications those are often useful. It is common to move the extern int foo;
declarations to a shared header file (foo.h in the example).
In C99, there's nothing called "program scope". In your example variable x
has a file scope which terminates at the end of translation unit. Variables y
and z
which are declared static
also have the file scope but with internal linkage.
C99 (6.2.2/3) If the declaration of a file scope identifier for an object or a function contains the storage class specifier static, the identifier has internal linkage
Also, the variable x
has an external linkage which means the name x
can is accessible to other translation units or throughout the program.
C99 (6.2.2/5) If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
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