如何避免在使用这种configurtation每一个函数传递配置变量 [英] How to avoid Passing config variable in every function which uses this configurtation
问题描述
我怎样才能避免传递配置变量中,使用此配置的每一个功能。
什么是做出这样的行为的最精确的方法。
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.
这是我的code:
main.c中
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.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;
}
//....
}
我所actully试图避免是在每个功能通过 config_names cnumbers
。
有接近这样的行为更聪明的方式?
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?
编辑:
我需要声明复杂的A,B,C,D,E,F;仅在main.c文件。这就是为什么我回避的全局变量
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.
这篇关于如何避免在使用这种configurtation每一个函数传递配置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!