0

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"+[];
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Phil Busby
  • 33
  • 5
  • 2
    You can't do this in c++ the way you've tried it. How about making `varBn[]` a 2D array like `varB[][]`. Then you can index into the appropriate array of `varB`. – cigien Jul 01 '20 at 12:38
  • 2
    put them into an array instead of encoding the index in their name – 463035818_is_not_an_ai Jul 01 '20 at 12:38
  • The term you are looking for is reflection and c++ doesn't support it. – Klaus Jul 01 '20 at 12:46
  • 1
    You can't remember it because you never did it. You solved your ultimate problem in some other way. – molbdnilo Jul 01 '20 at 12:52
  • molbdnilo - wise words, but I now remember it was in dBaseIII back in the 80's. When you get old the decades and memories all merge ;) Everyone else saw it, 2D the array!!! Goodness, you guys are helpful. Ironically I have 2D arrays elsewhere in the code so it was always staring at me blankly! – Phil Busby Jul 01 '20 at 13:23

1 Answers1

3

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.)

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185