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.

3
  • 1
    don't think there's a way to do this. But it would be a serious pain in the ass to debug if it were possible Commented Jun 10, 2014 at 8:09
  • Debug isn't an issue... Commented Jun 10, 2014 at 8:10
  • Plain simple : Not possible in C, however see asm may provide such functionality. Looks intresting Commented Jun 10, 2014 at 8:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.