How to use variable for (partial) variable name? (C)
Lets say I have the function
void do_work (foo?);
The ? represents a 0 or a 1 which will be the value of variable
int bar = 0;
There are also the variables
int foo0 = 0;
int foo1 = 0;
I am trying to inject the value of one variable into the name of another variable so that the function gets the full name o开发者_JAVA百科f either variable depending on preceding logic.
How can I do this?
(In this situation, i'm not worried about good or bad practice.)
C doesn't work in the way that perhaps you are thinking. You cannot dynamically refer to the name of a variable at runtime like you may be used to in other languages.
That said, the name of the function's arguments is irrelevant.
void do_work(int arg)
{
}
You don't have to match up the name of arg
with foo0
or foo1
. Now you can pass either variable into the function:
int foo0, foo1;
if (some_condition)
do_work(foo0);
else
do_work(foo1);
Now the function do_work
will be working on a copy of the variable passed. So if you change the variable's value inside the function, it will still remain the same outside the function. You can change that by returning a new value:
int do_work(int arg)
{
return arg + 1;
}
foo0 = do_work(foo0);
Lastly, it sounds like you want to use an array:
int foo[2]; // create two ints: foo[0] and foo[1]
do_work(foo[0]);
int i = 1;
do_work(foo[i]);
By special request of @dreamlax:
1) declare these variables as
__declspec( dllexport ) static int foo1;
__declspec( dllexport ) static int foo2;
2) Use HANDLE this_module = GetModuleHandle(NULL);
to obtain the current module
3) Obtain the name of the needed variable:
char vname[100];
sprintf(vname, "foo%d", bar);
4) Find it:
int* fooX = (int*)GetProcAddress(this_module, vname);
5) And, finally, you can use it:
do_work(fooX); // or *fooX, as you like
Use an array or pointer instead. You would access it with, e.g. foo[ind]
.
Use array:
int foo[2] = {0, 0};
and then you can type
do_work(foo[bar]);
To keep the original foo1
and foo2
variables, you can set up an array with pointers to those locations, and read/write to the vairables via the pointers in the array.
I.e.
int *fooArray[2];
fooArray[0] = &foo0;
fooArray[1] = &foo1;
...then you can call your function with:
do_work(*fooArray[bar]);
arrays are designed to hold values of homogeneous data types and nobody will use foo0, foo1 for this kind of requirement
Since you say you're not concerned with good or bad practice, you could implement the behaviour you want without introducing any new variables:
if (bar == 0)
do_work(foo0);
else if (bar == 1)
do_work(foo1);
else
puts("Uh oh, unexpected bar value!");
Here's a bad idea for you:
#define foo0 foo[0]
#define foo1 foo[1]
#define foobar foo[bar]
int foo[2];
int bar;
精彩评论