I am writing an application for my graduation coursework, in C, using GTK+ UI library. Sometimes I ask for user input, which I need to save for later use.

The doubt comes on how to store this data. I didn't want to create global variables because I was told countless times not to use them. However, I need to interchange data between functions which don't call each other directly (because of slot-signal pattern, I don't have a function that's always accessible after the event loop starts), thus needing some independent storage.

For this purpose I designed a getter-like function which reads similar to this:

char *store_data(char *data, int clear) {
    static char *stored_data = NULL;

    if(data == NULL) {
        if(clear) {
            stored_data = NULL;
        } else {
            return stored_data;
    } else {
        stored_data = data;

    return NULL;

Is such a construct OK or should I simply use a global variable instead?

  • 1
    I'd advise against this - I'd use a struct which holds all common state and explicitly pass a pointer to it into every function that uses it. If you don't like that, go back to a global variable. – lethal-guitar Mar 5 '14 at 13:53
  • @lethal-guitar the problem is I don't have a function that is always accessed, since GTK+ is event-driven. Where would I put this struct? – Mauren Mar 5 '14 at 13:54
  • 1
    I see.. well if all your event handlers are in one module, you can use a static global variable - it's only accessible inside that module, which I consider much better than a truly global variable. It's a bit similar to a class' private data in OO-languages. – lethal-guitar Mar 5 '14 at 13:58
  • You can then add a non-static "getter" function which returns the variable's value. – lethal-guitar Mar 5 '14 at 13:58
  • @lethal-guitar thanks, I think this is indeed a better approach. – Mauren Mar 5 '14 at 14:01

As I already said in the comments, I'd propose using a static global variable:

// Some *.c file:
static char *stored_data = NULL;

This will only be accessible from functions in the same module (.c-file), which is preferable to a truly global variable. If you like, you can still provide "getter" and "setter" functions in the same module, which are non-static and declared in the corresponding header file.

It's still global state, but it's now encapsulated in the relevant module. It's also clearer and cleaner than the "static local" approach, in my eyes.

Not the answer you're looking for? Browse other questions tagged or ask your own question.