Search code examples
cexternlifetime

Lifetime of "extern" variable in C?


What is the lifetime of variable p if it is declared as extern int p;

Is it static, dynamic, automatic or it has no lifetime because there is no linkage?


Solution

  • or it has no lifetime because there is no linkage?

    The keyword extern means a variable is only declared, that is no storage is allocated for it [1].

    The keyword extern has got nothing to do with the life time of a variable. That said, the life time/scope of a variable depends only on where exactly it occurs in the code.

    Note

    [1] When extern is used with an assignment like

    extern int i=5; 
    

    the keyword extern is ignored and the usual scope rules apply to the variable

    [2] Please check my other [ answer ] on this.


    Interesing: As Stephen Prata in his book C++ Primer Plus puts it, the keyword extern means "Use the variable by this name previously defined externally"