开发者

What is the difference between static int a and int a? [duplicate]

This question already has answers here: 开发者_运维问答 Closed 12 years ago.

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.


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).


Both are variable definitions, however, the static keyword applied to a variable in the "global declaration area" restricts that global variable to be seen only in the translation unit in which it is defined.


They are both in memory for the entire lifetime of the program. The variable that is declared static only has scope in the file in which it is declared where as the variable declared without static can be accessed from other files using an extern declaration.

Original source - http://bytes.com/topic/c/answers/860211-global-variable-static-global-variable


static int a is only accessible within that file. int b can be accessed with extern int b from a different file.


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.


A static variable's life extends across the lifetime of the program. However, scope rules still apply.

If you define your static variable outside of a method (normally at the beginning of the class) your variable will be available from anywhere within that class.

You can't change the value of these objects. They're normally used for storing things like API keys.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜