Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Is it possible to define variables dynamically?

Last night I was writing some code (C and VB2010) and I ran into a problem related to defining variables in my program. The variables needed depend on the number of entries added by the user and the number of users. Even using dynamic memory allocation we have a size limit, but I wonder about this type of thing sometimes. We can define as many variables as we need (to a limit of course) when writing the code, but can't we define more at runtime?

For example: say your whole program is done and when user says 'x', this cannot be created as variable; rather we require a variable to store that x. Why cant we make x a variable at runtime? Can't we build a bridge between compile-time and runtime with some rules?

share|improve this question

6 Answers 6

up vote 13 down vote accepted

Dynamically typed languages can define variables dynamically. Javascript has prototype based objects that can be defined and used as follows:

var myObj =  {}; // Empty object

// Define var1 in myObj
myObj.var1 = "Hello World";

// Use var1    
// Prints: Hello World

// Redefine var1 in myObj
myObj.var1 = 1336;

// Use var1 again
console.log(myObj.var1 + 1);
// Prints: 1337

In statically typed languages, such as Java, you need to solve it in a different manner. One easy way to emulate dynamic variables is to use the Map data structure (Map in Java, aka. Dictionary in .NET or Associative Arrays) much like how dynamically assigned variables do under the hood in languages such as Javascript:

Map<String, Object> vars = new HashMap<String,Object>();

// Define a variable:
vars.put("var1") = "Hello World";

// Use a variable:
// Prints: Hello World

// Redefine variable (1336 int is actually boxed into an Integer object):
vars.put("var1") = 1336;

// Use the variable again, type casting is needed:
System.out.println(1 + ((Integer) vars.get("var1")));
// Prints: 1337

So there are ways to emulate dynamic type variable handling in a statically typed language such as Java, but it will be more verbose than in a dynamically typed javascript.


Just to answer the OP in a more direct manner:

say your whole program is done and when user says 'x', this cannot be created as variable; rather we require a variable to store that x. Why cant we make x a variable at runtime?

As I alluded in my answer: Yes, you can emulate this behavior. I've created a small Java class to demonstrate the example and is available as a Gist. Feel free to run the example code and continue hacking on it.

share|improve this answer

It's most certainly possible in a sufficently dynamic language. However, it's very rarely regarded a good idea even in those languages. Here are a few reasons:

  • It is not needed. There are associative arrays, which by definition associate a name with a value, like variables do (they are in fact used to implement variables and object members - at least partly - in quite a few of the aforementioned languages). Hash tables are actually more powerful than variables in many (especially static) languages - you get a range of operations that don't necessarily make sense for variables, such as iterating over the keys.
  • It mixes up concerns. User input is separate from the names used in your implementation, user input shouldn't break the system because it happens to clash with one of your variable names. If you want to treat user input as variables, these should at least be in their own scope. And then you're back to manually using objects to collect user input in - call them a associative arrays or call them dynamically-created scopes, it's exactly the same thing. Except that associative arrays are conceptually simpler, more widely supported, possible more powerful, and more immediately recognized.

To make explicit what has been implied above: Using an associative array is like dynamically creating variables! It's merely restricted to its own scope, which is good and what you'd want anyway.

Also note how ridiclously hard it is to integrate this with static language's views on variables. C++ code doesn't have variable names at runtime, are you suggesting throwing out all the associated optimizations and introducing a ridiculously complicated system for dynamically compiling code, just so you can do the same thing as before under a different name?

share|improve this answer
Wish I could upvote this more than once. –  Zach Aug 23 '11 at 17:44

While the subject of dynamically creating code, compiling it and integrating it into the currently running application is interesting, I'm not sure it is what you are looking for.

Your problem which is reading an undefined number of entries in a format not know in advance and doing something with these does not seem very complicated, or maybe I am mistaken... Spoike's example code would be enough. If you want more than "maps", then yes you may need "meta beans", like for example dynamic beans (this is a Java example). Apache's BeanUtils library could be exactly what you are looking for.

Edit: in .NET you could use Spring.NET's framework, as it supports dynamic languages such as Groovy for example.

share|improve this answer

You can do this in c by dynamically modifying the code but you almost certainly don't want to for anything other than educational interest.

You've mentioned dynamic memory allocation (malloc and friends in c) and then talked about still having to have limits. Bear in mind that however you create variables there are still limits. If you are creating automatic variables at runtime then they are created on the (limited) stack. If you are creating globals they sit in (limited) var space.

I think I would solve this in c using malloc. Yes you have to place limits, but at least you can define what these limits are and handle them gracefully.

share|improve this answer

building anything at run-time can be done in two ways:

  1. Things which are dynamically entered by user
  2. Things which are equivalent to writing code

The first one is something almost all developers do. The number of items per page of a paged list, or the tax percentage, or the background color of a form, or anything of this essence is really easy to become dynamic.

However, what you ask is like trying to produce code at run-time. For example, if we have 2 variables:

string firstName;
int age;

now you want to introduce the third variable at run-time:

string[] interestes;

The only thing comes to my mind is through run-time code-generation, then recompiling it run-time, the calling it and executing it. For example, in .NET, the namespace of System.CodeDom is dedicated to this issue.

share|improve this answer
Thats absolutely right I want to create a variable at run time ! –  niko Aug 23 '11 at 13:23
+1 for mentioning System.CodeDom –  Jetti Aug 23 '11 at 13:37

What you're trying to do here is called meta-programming. Writing a code that writes code. Very popular thing with ruby (rails) developers. It's also possible in ObjectiveC. Probably other languages too, 'cause I'm no expert in others.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.