c++variablesc++14relative-addressing

Using variables to define variable names


I am sure that there is a very simple answer and I am perhaps just being forgetful, but I cannot remember how to use a variable to define the name of another variable. I cannot even think of a name of this process to search for existing answers.

I have a variable: VarA, which will be an integer 1, 2, 3, 4, etc.

I have another set of arrays VarBn[] where 'n' is related to VarA.

So, when VarA=1 I want to know VarB1[], and when VarA=2 ... VarB2[]

I currently have a very long and replicated switch statement...

switch(VarA)
  case 1: x=VarB1[]; break;
  case 2: x=VarB2[]; break;
  case 3: x=VarB3[]; break;
  case 4: x=VarB4[]; break;

But it would be far smaller function if it were just one line...

x=VarB+"contents of VarA"+[];

Solution

  • The term to search for is "nasty convoluted macro voodoo". But seriously, don't go there. Names of variables do not exist at runtime. What you want to do cannot be done in C++.

    However, whenever you name variables X1,X2,...XN then that variables actually want to be members of an array. If you use a 2D array then that switch becomes a simple:

    x = VarB[VarA];
    

    (btw x=VarB1[] does not look like valid syntax, and I cannot tell you if the above is correct without knowing what VarB and VarA actually are.)