How to avoid Passing config variable in every function which uses this configurtation

StackOverflow https://stackoverflow.com/questions/23525820

  •  17-07-2023
  •  | 
  •  

Вопрос

How can I avoid passing a "config" variable in every function which uses this configuration. what is the most accurate way to make such a behavior.

This is my code: main.c

/* Complex Numbers Linking to proper variable */
typedef struct tagConfigNames {
    char name;
    complex *cnum;
} config_names;

/* Set command to function */
struct {
    char *name;
    void (*func)(config_names[]);
} cmd[] = {{"read_comp", read_comp}, {"print_comp", print_comp}, {"halt", halt},{"not_valid", NULL} };

int main()
{
    complex a,b,c,d,e,f;
    config_names cnumbers []= {{'a', &a}, {'b', &b}, {'c', &c}, {'d', &d}, {'e', &e}, {'f', &f},
                {'A', &a}, {'B', &b}, {'C', &c}, {'D', &d}, {'E', &e}, {'F', &f},
                {'#', NULL}};
    char command[30];
    int i;

    /* Run Forever */
    while(1) 
    {
        if (scanf("%s", command) == 1) {
            for (i = 0; cmd[i].func != NULL; ++i) {
                if (strcmp(command, cmd[i].name) == 0) 
                    break;
            }

            if (cmd[i].func == NULL) {
                printf("Error: no such command!\n");
            } else {
                (*(cmd[i].func))(cnumbers);
            }
        }
    }

    return 0;
}

complex.c

complex* find_complex_number(config_names cnames[], char ch)
{
    int i;
    for (i = 0; cnames[i].cnum != NULL; i++) {
        if (cnames[i].name == ch)
            break;
    }

    return cnames[i].cnum;
}

void read_comp(complex_names cnames[]) 
{
    //....

    if ((complex_num = find_complex_number(cnames, ch)) == NULL) {
        printf("Error: No such complex number\n");
        return;
    }
    //....
}

What I am actully trying to avoid is the config_names cnumbers which is passed in every function. is there a smarter way to approach such a behavior?

EDIT:

I need to declare the complex a,b,c,d,e,f; only on the main.c file. thats why i'm avoiding global variables

Это было полезно?

Решение

If the "configuration" is constant for each thread of the application you might consider defining it globally.

Другие советы

If the config is constant for every thread, or you're not using threads, you may use a global variable. Otherwise you can use Thread Local Storage, it will be like a global variable but specific to each thread.

To expand on the above, you might want to gather all functions depending on this in a file, and make the global (or thread local) variable static there, so as keeping polution to a minimum.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top