You can't do it directly in C.
You can do something like this however:
#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;
}
Output (ideone):
variable "ABC" = 111
variable "DEF" = 222
variable "XYZ" = 333
variable "DEF" (selected randomly) = 222
Since GetVarPtr()
returns a pointer to a variable, you can not only get the variable's value, but also set it.
You can even hide the pointer thing behind a macro:
#define VARIABLE(NAME) (*GetVarPtr(NAME))
In this way you can do things like this (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"));