Skip to main content

Functions and Local Variables

Now that the philosophy session is over we have to return to the details - because as it stands the demo function will not work. The problem is that the variable total isn't declared anywhere. A function is a complete program sub-unit in its own right and you can declare variables within it just as you can within the main program. If you look at the main program we have been using you will notice it is in fact a function that just happens to be called "main"! So to make demo work we have to add the declaration of the variable total:

demo()

{

int total;

printf("Hello");

total=total+1;

}

Now this raises the question of where exactly total is a valid variable. You can certainly use total within the function that declares it - this much seems reasonable - but what about other functions and, in particular, what about the main program? The simple answer is that total is a variable that belongs to the demo function. It cannot be used in other functions, it doesn't even exist in other functions and it certainly has nothing to do with any variable of the same name that you declare within other functions.

This is what we hinted at when we said that functions were isolated chunks of code. Their isolation is such that variables declared within the function can only be used within that function. These variables are known as local variables and as their name suggests are local to the function they have been declared in. If you are used to a language where every variable is usable all the time this might seem silly and restrictive - but it isn't. It's what makes it possible to break a large program down into smaller and more manageable chunks.

The fact that total is only usable within the demo function is one thing - but notice we said that it only existed within this function, which is a more subtle point. The variables that a function declares are created when the function is started and destroyed when the function is finished. So if the intention is to use total to count the number of times the &&&&demo function is used - forget it! Each time demo is used the variable total is created afresh, and at the end of the function the variable goes up in a puff of smoke along with its value. So no matter how many times you run demo total will only ever reach a value of 1, assuming that it's initialised to 0.