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?
5
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.
2