Thinking Local...




Document: Software Engineering 1: Course Notes

next A (Short) Digression
up Moving Data Around
previous Thinking Global...

Thinking Local...

OK, so much for using global variable for co-ordinating or sharing data access between functions in a C function. What is the alternative?

The alternative mechanism arises if we choose to make the data - the variables - local to individual functions. Local variables are declared immediately after the opening brace of a function definition. Local variables are visible and accessible only within the function in which they are defined. Indeed, the storage for the variables is only allocated at all when the function is invoked and is deallocated again when the function terminates - so the variables only actually "exist" as long as the function is active.

Now it follows directly from the "privacy" of local variables that they cannot be used to share data between functions. Therefore, if our functions are using local variables, and if we need to share this data, we need some mechanism for "passing" the data from one function to another. This generally arises just precisely when one function is calling another (call the latter the sub-function). Actually there are then two sub-issues: getting data from the function to the sub-function, and getting data (results) back to the calling site from the sub-function. C provides separate mechanisms, with rather different characteristics to deal with these two directions of data flow - from calling site to called function, and from called function back to calling site.

Note that in any particular case of one function calling another we may need to transfer data in only one of the two directions, so they really are quite separate. Indeed, as we have already seen with the use of global variables above, we can have functional decomposition of a program without using either of these data transfer mechanisms. In designing a program - in breaking it up into functions - each case has to be assessed individually.




Document: Software Engineering 1: Course Notes

next A (Short) Digression
up Moving Data Around
previous Thinking Global...



McMullin@ugmail.eeng.dcu.ie
Wed Apr 12 19:40:14 BST 1995