Monday, January 31, 2011

1.10 External Variables and Scope

  • Variables (automatic) in a function are local or private to the particular function
  • Each local variable in a function comes into existence only when the function is called, and disappeared when the function exited
  • Automatic variables do not retain their values from one call to the next, and must be explicitly set upon each entry. If they are not set, they will contain garbage
  • External variables are globally accessible, exist permanently and retain values after function returned, oppose to automatic variables
  • An external variable must be defined, exactly once, outside of any function; to set aside storage for it
  • The external variable must also be declared in each function that want to access it; this states the type of the variable. The declaration may be an explicit "extern" statement or may be implicit from context
  • If the definition of an external variable occurs in the source file before its use in a particular function, then there is no need for an extern declaration in the function
  • Common practice is to place definition of all external variables at the beginning of source files and then omit all extern declarations
  • If a program is in several source files, and a variable is defined in file1 and used in file2 and file3, then the extern declarations are needed in file2 and file3 to connect the occurrences of the variable
  • The usual practice is to collect extern declaration of variables and functions in a separate file (header)

No comments:

Post a Comment