Possible Duplicate:
Difference between 'global' and 'static global'
What is the difference between statements 1 and 2 :-
#include <stdio.h>
//In the global declaration area
static int a; // 1.
int b; // 2.
Thanks for help.
Answers. int is a datatype for a variable storing integer values. static int is a variable storing integer values which is declared static. If we declare a variable as static, it exists till the end of the program once initialized.
1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is called, but an auto variable can't be used for this purpose.
Using 'int' in a class means an integer field exists on each instance of the class. Using 'static int' means an integer field exists on the class (and not on each instance of the class)
Global variables are stored in Data Segment of process. Global variable's life is until the life of program and it can be accessed by other files using extern keyword. Static variable can be declared outside of all functions or within a function using static keyword before the data type of variable .
A static
global variable is local to the translation unit it is defined in. So, if you define static int a;
in two different translation units, this will create two independent variables. If you define a non-static global variable int b;
in two translation units, you will experience a linker error (but you can use extern int b;
in one of the two translation units to tell the linker that it should use the global variable from the other translation unit).
static int a;
int b;
a
has internal linkage. b
has extern linkage.
C99 6.2.2
6.2.2 Linkages of identifiers
1) An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. There are three kinds of linkage: external, internal, and none.
2) In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity.
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.
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