Page 1 of 3 123 LastLast
Results 1 to 10 of 21

Thread: C Dynamic Variable Creation

  1. #1
    Join Date
    Sep 2009
    Beans
    197
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    C Dynamic Variable Creation

    I would like to dynamically create variables on the fly in a C program. For instance, if I have a loop that loops 3 times, I want it to create:

    • int var1 = somenumber
    • int var2 = somenumber
    • int var3 = somenumber


    Is this possible in C, and if so, how would I go about doing this.
    lewisforlife

  2. #2
    Join Date
    Jun 2007
    Location
    Maryland, US
    Beans
    6,288
    Distro
    Kubuntu

    Re: C Dynamic Variable Creation

    No, dynamic variable creation is not possible in C.

    Can you please elaborate on what you require? You can allocate an array, of whatever size you require, during runtime, and assign values to the array.

    Something like:
    Code:
    int* array = malloc(numValues * sizeof(int));
    
    if (array)
    {
       for (int i = 0; i < numValues; ++i)
       {
          array[i] = someNumber;
       }
    }
    else
    {
       /* failure to allocate */
    }

  3. #3
    Join Date
    Aug 2006
    Location
    60°27'48"N 24°48'18"E
    Beans
    3,458

    Re: C Dynamic Variable Creation

    Has to be done by usage of an appropriate data structure... array, a hash, tree... keyed property list...
    LambdaGrok. | #ubuntu-programming on FreeNode

  4. #4
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: C Dynamic Variable Creation

    Quote Originally Posted by lewisforlife View Post
    I would like to dynamically create variables on the fly in a C program. For instance, if I have a loop that loops 3 times, I want it to create:

    • int var1 = somenumber
    • int var2 = somenumber
    • int var3 = somenumber


    Is this possible in C, and if so, how would I go about doing this.
    You can't. The only two languages I am aware of being able to do this are Python and Lisp. Maybe Perl and Ruby can do it too, but I don't remember.

  5. #5
    Join Date
    Aug 2007
    Location
    127.0.0.1
    Beans
    1,800
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: C Dynamic Variable Creation

    The closest thing to assigning names and values in runtime is with a Hash. Although, I assume that the OP is a beginner, so stick to arrays (which, in theory, are a particular type of hash where f(i) = i*size).
    "Just in terms of allocation of time resources, religion is not very efficient. There's a lot more I could be doing on a Sunday morning."
    -Bill Gates

  6. #6
    Join Date
    Aug 2006
    Location
    60°27'48"N 24°48'18"E
    Beans
    3,458

    Re: C Dynamic Variable Creation

    Quote Originally Posted by Can+~ View Post
    Although, I assume that the OP is a beginner, so stick to arrays (which, in theory, are a particular type of hash where f(i) = i*size).
    Which are all just mappings (functions) from keys to values, and particularly in this case in Lisp terms we're looking at the environment keys-to-values mapping, which the expression is evaluated in terms of...

    *Sigh*... it's all Lisp and so few know it
    LambdaGrok. | #ubuntu-programming on FreeNode

  7. #7
    Join Date
    Dec 2007
    Beans
    1,042
    Distro
    Ubuntu Karmic Koala (testing)

    Re: C Dynamic Variable Creation

    You can't create a variable on the fly. You can create an array of variables of any length (and use realloc to resize the array dynamically,) but then you have to use numbers instead of names.

    You can also use a hash table or associative array to associate names with values, but this has a performance penalty and it's kind of a pain besides. (You can't treat the values as variables, but as the output of a function.)


    Try an interpreted language. Lua, shell, and Python (in order from most to least) have the ability to do this kind of thing effortlessly. Apparently Lisp is the champion for this kind of stuff, but I've never used it. Can't say I've really tried any interpreted language besides those three, actually.
    He that would make his own liberty secure must guard even his enemy from oppression; for if he violates this duty he establishes a precedent that will reach to himself.
    -Thomas Paine

  8. #8
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: C Dynamic Variable Creation

    An example on how to do this in Common Lisp

    Code:
    (defmacro dyn (basename &rest maps)
      `(progn
         ,@(loop for pair in maps
              collect
                `(defvar ,(intern (string-upcase (format nil 
                                                         "~a~a" 
                                                         basename
                                                         (car pair))))
                   ,(cadr pair)))))
    
    ; SLIME 2009-07-02
    CL-USER> (dyn "abc" (7 8) (77 'u))
    ABC77
    CL-USER> abc7
    8
    CL-USER> abc77
    U
    EDIT: Improved it a bit.
    Last edited by nvteighen; December 31st, 2009 at 02:53 PM.

  9. #9
    Join Date
    Dec 2009
    Location
    Norway
    Beans
    Hidden!
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: C Dynamic Variable Creation

    Quote Originally Posted by nvteighen View Post
    An example on how to do this in Common Lisp

    Code:
    (defmacro dyn (basename &rest maps)
      `(progn
         ,@(loop for pair in maps
              collect
                `(defvar ,(intern (string-upcase (format nil 
                                                         "~a~a" 
                                                         basename
                                                         (car pair))))
                   ,(cadr pair)))))
    
    ; SLIME 2009-07-02
    CL-USER> (dyn "abc" (7 8) (77 'u))
    ABC77
    CL-USER> abc7
    8
    CL-USER> abc77
    U
    EDIT: Improved it a bit.

    Or one could use PROGV which will generate dynamic bindings 100% at run-time:

    Code:
    CL-USER> (flet ((test ()
                      (format t "test A: ~A~%" a)
                      (format t "test B: ~A~%" b)))
               (progv (list 'a 'b) (list 1 2)
                 (test)
                 (format t "A: ~A~%" a)
                 (format t "B: ~A~%" b)))
    test A: 1
    test B: 2
    A: 1
    B: 2
    NIL
    Quite cool. Note that the two calls to LIST really are evaluated at run-time, which means that they could be passed in as arguments or variables.

    Just to show more clearly that the TEST function and the PROGV things really are 100% separate:

    Code:
    CL-USER> (defun test () 
               (format t "test A: ~A~%" a)
               (format t "test B: ~A~%" b))
    TEST
    
    CL-USER> (progv (list 'a 'b) (list 1 2)
               (test)
               (format t "A: ~A~%" a)
               (format t "B: ~A~%" b))
    test A: 1
    test B: 2
    A: 1
    B: 2
    NIL
    CL-USER>

    Wrt. the OP I would use STD:MAP or STD:HASH (C++0x; GCC supports this via the -std=gnu++0x option) or using C I'd go for the GLib library: http://library.gnome.org/devel/glib/...sh-Tables.html .. which pretty much is available "everywhere".
    Last edited by worseisworser; December 31st, 2009 at 03:29 PM.

  10. #10
    Join Date
    Dec 2007
    Beans
    1,042
    Distro
    Ubuntu Karmic Koala (testing)

    Re: C Dynamic Variable Creation

    Here's how you create new globals in Lua:
    Code:
    max@server:~$ lua
    Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
    > _G["foo"] = "bar"
    > print (foo)
    bar
    > varname = "spam"
    > _G[varname] = "eggs"
    > print (varname)
    spam
    > print (spam)
    eggs
    > print (_G["varname"])
    spam
    > print(_G[_G["varname"]])
    eggs
    >
    _G is a special table that points to the global scope. I suppose the language is sort of "cheating" by doing it this way, but it works well.

    You can also use the dot "." if you don't want to use strings as names, but this has its limits:
    Code:
    > print(_G.varname)
    spam
    > print(_G._G.varname) -- _G contains itself because _G is a global, so this doesn't quite work.
    spam
    > print(_G.(_G.varname)) -- This doesn't work either
    stdin:1: '<name>' expected near '('
    > print (_G[_G.varname]) --this does work
    eggs
    >
    Also, heck, why not? Let me show you what some of this stuff is good for:
    Code:
    > _G["print"]("hello") -- functions are part of _G as well
    hello
    > _G["PRINT"]=function(str) print ( string.upper(str) ) end -- create a wrapper around "print"
    > PRINT ("hello")
    HELLO
    > _G["_print"]=_G["print"]
    > _G["print"] = function(str) _print (string.upper (str)) end -- completely replace "print"
    > print "hi"
    HI
    >
    Last edited by MaxIBoy; December 31st, 2009 at 07:13 PM.
    He that would make his own liberty secure must guard even his enemy from oppression; for if he violates this duty he establishes a precedent that will reach to himself.
    -Thomas Paine

Page 1 of 3 123 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •