0

I'm looking for a way to get a char* from a user and using this string to refer to a variable in my program. This resembles the pre processesor's paste option ##. For example say I have a function: f(int num); And variables int x = 1, z = 2;

And I want to be able to do something like the following:

int y=f(##arg [1]); \\should be equivalent to: int y=f(x) assuming argv[1] ="x"

Or if the input is "z" then send z to f()...

Is there some way this can be achieved?

Thanks.

Edit: The solution doesn't have to be perfectly dynamic, I can live with some assumptions, like making the available variables strict, i.e only have a set of allowed variable names.

ZivS
  • 2,094
  • 2
  • 27
  • 48

2 Answers2

4

You cannot do that directly, in C.

C is a compiled language, with no built-in introspection support.

When the program runs, the variable names are gone. They are just needed by the compiler to know what you want to do, to refer to various pieces of data.

So, to get this behavior, you must manually set up some form of look-up table where the names are kept (as strings), and then implement the search yourself.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

No this is not possible in C. This is because it is not a reflective language (unlike Java). All variable symbols are lost during compilation.

One possibility would be to use a hash map to build up a symbol table for run-time use (with the names and pointers to the variables as the keys and values respectively), but given your use-case I'd advise against that.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483