Accessing a variable by it's name, from a string

Discussion in 'Mac Programming' started by mathcolo, Feb 26, 2010.

  1. mathcolo macrumors 6502a

    Sep 14, 2008
    While the title of this thread might not make all that much sense, I'm going to attempt to explain:

    I have this small C program, and I'm trying to do something that I would expect to be pretty easy (It's command line). I want this program to ask for user input, and then access a variable that the user enters. So it would work like this:

    double a = 1;
    double b = 2;
    double c = 3;
    (program asks for user input)
    (user enters "a" (without quotes))
    (Then, the program would output 1, because that's the value of a)
    Hopefully that made sense. If there's no way to write a program that does exactly that, how would I write one that works similar? This is just a small part of a larger project. Thanks for any help and suggestions!

    Edit: Also, this has to be done without an if statement, so that it's extensible. That's where it seems to get more complicated...
  2. notjustjay macrumors 603


    Sep 19, 2003
    Canada, eh?
    How about a key-value table, where each value is keyed to a unique string and the user is asked to enter the string. Then you just look it up in the table.

    Edit: for example, here's how you could use a C++ STL map to accomplish what you need:

    That may fall outside your requirements (you did say C, and not C++) but whatever environment you're in should have some kind of hash table construct which would work similarly.
  3. larkost macrumors 6502a

    Oct 13, 2007
    To give a little more information: the reason you can't just do the "obvious" thing and check against the variable names is that in c once compiled those labels you put on things like variables or functions devolve into locations. In non-debug builds (so-called "striped" builds) there is nothing left to associate the names you gave things with their locations (although you can produce files while compiling to allow you to do this for crash tracing).

    This makes thing much, much faster, but does preclude doing what you would like. I should note that in many scripting languages you could do exactly this sort of thing, but it would still be faster to use some sort of a lookup table to handle this.
  4. mathcolo thread starter macrumors 6502a

    Sep 14, 2008
    Oh, yeah, that completely makes sense. I forgot about that. I'll just have to do a KVC table or something similar. Thanks for the insight!

Share This Page