Friday, November 25, 2011

extern and more

Two more :)

1. What is the difference between declaration and definition of a variable ?
     The definition allocates memory for the variable, whereas the declaration just tells the compiler that the memory for the variable is allocated somewhere else in the program. Note that a variable or a function can be "declared" any number of times, while it can be "defined" only once.


2. What are "extern" variables/functions ?
     When a variable/function is declared as extern in a file it means that the variable/function is defined somewhere in the program and that it can be used harmlessly in this file. The extern keyword extends the scope of the entity beyond the file in which it is defined.
     The functions are by default "extern" entities even though we don't use it while declaring or defining the function. So extern doesn't make much sense when used with functions.
     For variables, however, extern keyword has many implications. It tells the compiler that the definition of the variable is elsewhere and forces the statement to declare the variable. If extern is not used then the statement can be treated as a declaration or a definition depending on the compiler, which will analyze the modules and decide if the statement is a definition or a declaration. On the other hand, if you want to force the statement to define a variable then initialize it, this will make sure the memory is allocated for the variable.
    Check this for more information.

No comments:

Post a Comment