Thread: User defined Variable name

  1. #1
    Registered User
    Join Date
    Aug 2008

    User defined Variable name


    i'm trying to learn C programming in order to complete a small project, but am getting a bit stuck with an issue.....

    i need to take user input and then assign an integer value to the input.

    is it possible to generate variable names as a program runs - or do they have to be generated prior to compiling?

    would it be possible to achieve this using pointers instead.


  2. #2
    The larch
    Join Date
    May 2006
    You can't create real variables at runtime.

    You could use a [hash]map, though.

    In C++ it might look like this:
    map<string, int> var_map;
    string name;
    int value;
    cin >> name >> value;
    var_map[name] = value;
    In C you'd probably have to code the map yourself, unless you can find a library for that.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Or not a map,
    struct record
        char name[32];
        int value;
    /* ... */
    struct record variables[32] = {{"", 0}};
    Granted it's slower. If you need more speed, look into a hashtable.

    And no, you do not need to "create" the variables at runtime in your case...
    int input = 0;
    char line[256] = {0};
    fgets(line, sizeof(line), stdin);
    sscanf(line, "&#37;d", input);

  4. #4
    Registered User
    Join Date
    Aug 2008
    thanks - looks like just what i was after


  5. #5
    and the hat of sweating
    Join Date
    Aug 2007
    Toronto, ON
    Why do you care what the name of the variable is at runtime? The compiler doesn't keep the name anyways; it just converts it to an address.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Choosing a variable based on user text input.
    By Compiling... in forum C++ Programming
    Replies: 7
    Last Post: 11-01-2005, 01:21 AM
  2. User defined functions
    By alexpos in forum C Programming
    Replies: 2
    Last Post: 10-23-2005, 02:53 PM
  3. DLL compiling question
    By Noose in forum Windows Programming
    Replies: 2
    Last Post: 12-16-2004, 07:16 AM
  4. need to read a User defined file during runtime
    By john_newbie in forum C Programming
    Replies: 8
    Last Post: 03-06-2004, 02:08 AM
  5. win32 and user defined classes
    By paulf in forum Windows Programming
    Replies: 4
    Last Post: 04-16-2002, 06:12 PM