#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Location
    India
    Posts
    65
    Rep Power
    20

    Question regarding extern


    I was reading The C programming language by D.R. & B.K. I am not getting the meaning of the following line.Kindly help me with the example.

    In certain circumstance ,the extern declaration can be omitted.If the definition of an external variable occur in the source file before its use in a particular function,then there is no need for an extern declaration in the function.In fact the common practice is to place definitions of all external variables at the beginning of the source file ,and omit all extern declaration.

    Page Number :33
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    1
    Rep Power
    0
    This means that if your function refers to "global" variables (as opposed to "local" ones that are only known to that function) you don't have to declare them, provided they were defined earlier in the file. The compiler would realise that max and longest in K&R's example refer to the max and longest declared at the top of the file without being told specifically by the external declaration. So the external declaration is redundant.
    You would need it if the definition occurred *after* the function in the source file.
    However, all C I've seen has the "global" variables declared before the functions I've never seen any external variables re-declared inside a function.
    I've put "global" in quotes here as I'm using the term in the sense of global within that file.
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,109
    Rep Power
    1802
    While the statement is correct, I think they are confusing a simple issue.

    I would say simply extern is required only to distinguish a data declaration from a data instantiation. For example:

    Code:
    extern int foo ;  // declaration
    int foo = 255 ;  // instantiation (with initialiser)
    
    extern int bar ; // declaration
    int bar ; // instantiation (without initialiser)
    extern is always explicit for a definition not within a function.

    All that said, your book should hardly be encouraging teh use of global data declarations in any case. It is just poor practice.

    extern is entirely unnecessary for function declarations, because these are distinguished from definitions by having no function body. They are deed for data declarations because a data declaration need not have an explicit initialiser.
    Last edited by clifford; May 18th, 2013 at 12:19 PM.

IMN logo majestic logo threadwatch logo seochat tools logo