Thread: Global variables

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    38

    Global variables

    Hello people.

    How dangerous it is to use global/external variables?
    Suppose I have several ".c" and ".h" files in a project. This struct is defined:

    Code:
    struct example	
    {
    	char *element_A;
    	char *element_B;
    };
    Now, I want to read and modify both elements from different not-linked functions from different .c files?

    Is to define this struct like a global variable the best solution?

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    "Best" solution depends on the problem (that sounds like a cop-out, but it's true).

    The problem with global variables is that any old function can modify them. Of course, if you're especially careful that's not going to be an issue, but often you need to make some sort of change that will inadvertently cause you problems.

    A safer approach is to create a .c file that has your struct in it, global and static. Then that .c file exports an interface that's used to access the struct. That way you have complete control over your variables; you can't accidentally set one of your pointers to in invalid value; or, at least, there's only one place you can do it instead of ten, or fifty!

    For a smaller program, if you trust yourself, you can probably get away with simple global variables. It's easier than defining a new interface and really, there's nothing fundamentally wrong with globals. If you wind up having something that's used in a lot of places, I might recommend encapsulating it for safety and simplicity's sake. For example, you might decide to change your pointers to arrays (for whatever reason). With a proper interface, you don't have to worry about changing all your strdup() calls to strcpy(), etc. Just change it once in the interface's implementation and it magically still works.

    So, it can be dangerous, but it's not an inherently bad thing to use globals.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 08-06-2008, 09:59 AM
  2. scope of global variables
    By laertius in forum C++ Programming
    Replies: 4
    Last Post: 10-15-2006, 01:59 AM
  3. global variables - okay sometimes...?
    By MadHatter in forum C++ Programming
    Replies: 21
    Last Post: 01-21-2003, 04:23 PM
  4. global variables
    By rdnjr in forum Linux Programming
    Replies: 0
    Last Post: 01-07-2003, 10:28 AM
  5. Global variables? Bad! Yes, but to what extent?
    By Boksha in forum C++ Programming
    Replies: 6
    Last Post: 05-26-2002, 04:37 PM