Professional Documents
Culture Documents
2.5. Declaration of Variables
2.5. Declaration of Variables
Declaration of variables
You may remember that in Chapter 1 we said that you have to declare the
names of things before you can use them (the only exceptions to this rule
are the names of functions returning int, because they are declared by
default, and the names of labels). You can do it either by using
adeclaration, which introduces just the name and type of something but
allocates no storage, or go further by using a definition, which also
allocates the space used by the thing being declared.
The distinction between declaration and definition is an important one,
and it is a shame that the two words sound alike enough to cause
confusion. From now on they will have to be used for their formal
meaning, so if you are in doubt about the differences between them,
refer back to this point.
The rules about what makes a declaration into a definition are rather
complicated, so they will be deferred for a while. In the meantime, here
are some examples and rule-of-thumb guidelines which will work for the
examples that we have seen so far, and will do for a while to come.
/*
* A function is only defined if its body is given
* so this is a declaration but not a definition
*/
int func_dec(void);
/*
* Because this function has a body, it is also
* a definition.
* Any variables declared inside will be definitions,
* unless the keyword 'extern' is used.
* Don't use 'extern' until you understand it!
*/
int def_func(void){
float f_var;
/* a definition */
int counter;
/* another definition */
int rand_num(void);
/* declare (but not define) another function */
return(0);
}