Preferences?




Document: Software Engineering 1: Course Notes

next Recursion
up Moving Data Around
previous Getting data back out of a function

Preferences?

We have seen two radically different styles of getting information into and out of functions: the use of global variables and the use of parameters and return values. Which is best?

Unfortunately there is no simple answer. Both kinds of mechanism are provided in C precisely because, in different circumstances they each have their own advantages.

For people just starting out to learn to program the global variable mechanism is conceptually easier to deal with, and actually syntactically easier to use in programs. Therefore I recommend that you start out by using this mechanism, unless you have some specific reason for doing otherwise.

However, quite quickly you will probably discover some of the drawbacks of using global variables. At that point it is worth getting familiar with both parameter and return value mechanisms and trying them out.

Once you are technically happy that you can use both kinds of style then, with experience, you will get a feel for the particular circumstances in which each is appropriate. But: until you are comfortable with judging this I recommend that you actually try to avoid or minimise your use of global variables. You will find that this requires you to think rather harder about how to design your programs; and will also make the design and coding somewhat more cumbersome at times. However, it is a fact that the use of global variables makes programs prone to a variety of subtle problems and bugs - due to non-obvious and un-intended interactions between functions, via changes in global variables. Such bugs are particularly difficult to isolate and correct. Therefore you will find that avoiding the use of global variables - except where they have some overwhelming advantage to recommend them - will save you a lot of program development time in the long run.




Document: Software Engineering 1: Course Notes

next Recursion
up Moving Data Around
previous Getting data back out of a function



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