#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;
}
