您不能直接在 C 中执行此操作。
但是,您可以执行以下操作:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Binding
{
int* pIntVar;
const char* IntVarName;
struct Binding* pNext;
} Binding;
Binding* Bindings = NULL;
void BindVar(const char* IntVarName, int* pIntVar)
{
Binding* b;
if ((b = malloc(sizeof(Binding))) != NULL)
{
b->IntVarName = IntVarName;
b->pIntVar = pIntVar;
b->pNext = NULL;
if (Bindings == NULL)
{
Bindings = b;
}
else
{
Binding* bs = Bindings;
while (bs->pNext != NULL)
{
bs = bs->pNext;
}
bs->pNext = b;
}
}
else
{
fprintf(stderr, "malloc() failed\n");
exit(-1);
}
}
int* GetVarPtr(const char* IntVarName)
{
Binding* bs = Bindings;
while (bs != NULL)
{
if (!strcmp(bs->IntVarName, IntVarName))
{
return bs->pIntVar;
}
bs = bs->pNext;
}
fprintf(stderr, "variable \"%s\" not bound yet!\n", IntVarName);
exit(-1);
}
int main(void)
{
int ABC = 111, DEF = 222, XYZ = 333;
const char* varName = NULL;
BindVar("ABC", &ABC);
BindVar("DEF", &DEF);
BindVar("XYZ", &XYZ);
printf("variable \"%s\" = %d\n", "ABC", *GetVarPtr("ABC"));
printf("variable \"%s\" = %d\n", "DEF", *GetVarPtr("DEF"));
printf("variable \"%s\" = %d\n", "XYZ", *GetVarPtr("XYZ"));
// Pick a variable randomly by name
switch (rand() % 3)
{
case 0: varName = "ABC"; break;
case 1: varName = "DEF"; break;
case 2: varName = "XYZ"; break;
}
printf("variable \"%s\" (selected randomly) = %d\n", varName, *GetVarPtr(varName));
return 0;
}
输出(ideone):
variable "ABC" = 111
variable "DEF" = 222
variable "XYZ" = 333
variable "DEF" (selected randomly) = 222
由于GetVarPtr()
返回一个指向变量的指针,你不仅可以获取变量的值,还可以设置它。
您甚至可以将指针隐藏在宏后面:
#define VARIABLE(NAME) (*GetVarPtr(NAME))
通过这种方式,您可以执行以下操作(ideone):
VARIABLE("ABC") = 1;
VARIABLE("DEF") = 2;
VARIABLE("XYZ") = 3;
printf("variable \"%s\" = %d\n", "ABC", VARIABLE("ABC"));
printf("variable \"%s\" = %d\n", "DEF", VARIABLE("DEF"));
printf("variable \"%s\" = %d\n", "XYZ", VARIABLE("XYZ"));