declaration and definitions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vensriram
    New Member
    • Aug 2010
    • 48

    declaration and definitions

    Code:
    int a;
    The above snippet is a declaration. Whether it is a definition too.....
    Because one website that i referred tells that only
    Code:
    [B]extern [/B]int i;
    is a declaration.
    All the other types are both declaration and definition.
    Is it true?
    If yes kindly clarify when a variable is declared and when the same is defined?
    Thanks in advance.......
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    A variable is defined when it occupies memory.

    Otherwise, it is declared.

    Therefore:

    1) int i; is a definition. The variable i is created and occupies memory.

    2) extern int i; is a declaration. The variable i is an int but is is not in this source file. That is, it is defined in some ther file with external linkage.

    3) extern int i = 10; is a definition. A variable i is reated with a value of 10. The variable is to be accessible from other files that use extern int i;

    Based on (3), you can define variables that are accessible from other files that use extern. This is important for const variables which are by default not accessible from other files by using extern. That is you define your const variable with external linkage:

    extern const int i = 10;

    Now other files can access this variable by using:

    extern const int i;

    Comment

    Working...