The main reason you want to stay away from declaring global variables is because you dont want variables that any function can modify or access. This is especially important in larger systems. Variables could get modified and you wouldnt know it. That is what is nice about C++, you can declare a variable private to a given class.
You can also implement data hiding in C. Instead of making a variable "global," use static to prevent it from being exported to the linker and then write access functions:
The advantage is that the user must use the accessor functions to access or change members of the struct. The disadvantage is that the user can only create pointers to struct foo, because it is an incomplete type.
Russ
bobbitts@hotmail.com
Thank you all for the explaination. It's clear but kinda complicate to me. I just want to declare a global variable so I can access to it in any function. If I declare it locally, then I have to re-declare it in each function then I have to pass it out...too complicate. But I guess this is how C works. It's much easier in VB.
Steve McConnell, in his book, "Code Complete, A Practical Handbook of Software Construction" says these are the main reasons to limit the use of globals:
1) Inadvertent changes to global data
2) Bizarre and exciting aliasing problems with global data.
3) Re-entrant code problems with global data.
4) Code reuse hindered by global data.
5) Modularity and intelliectual manageability damaged by global data.
McConnell agrees with Russ above to use access routines to retrieve and update your global data. In fact, McConnell, at least during development, likes to lock his globals. You can check a global out, but it can't be changed until it's checked back in.
Kendel, this was an interesting thread. Thanks for starting it.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.