-
random variable names
I know that we have structs, arrays and so on to avoid this, but only curiosity.
In PHP (C based) i could create random variable names like $varXXX, where XXX is a random number. And i could do that forever (until the memory pops out xD)
In C how can i do it?
-
you can't is the simple answer. Like you said, we have arrays and malloc to avoid this.
QuantumPete
-
You don't. "Creating" variables at runtime is not possible in compiled languages. It is one of the advantages with (some) interpreted languages, such as PHP. In (nearly all) compiled languages, all variables have to be declared before they are used.
There is usually a way to do the same thing, and it usually involves pointers and/or arrays.
If you describe the actual problem you are trying to solve, I'm sure someone can come up with a suitable solution.
--
Mats
-
Its not a problem based question, just curiosity out of the box.
Thanks! ;)
-
It's not very easy in C, but in C++, it's usually a snap.
What you would do is use a map to "translate" a string into a specified address or storage unit (variable of some type). In C++, there's an already existing map. In C, there is not.
-
Interesting. We know that variable names can not be generated on the fly in compiled languages, but you can implement functions to handle a variable amount of arguments with the use of variadic macros.
More food for thought.
-
I was trying to come up with something sort of along the same lines. My problem was I wanted to be able to reference an array of structs based on the ID of the menu item being clicked to toggle them. The IDs don't start at 0 like an array though. Can an array/struct be defined in such a way that I can reference it using a variable? Like Templates.(VAR).Name? Or can arrays be defined to not start at 0? Like in VB6, you could do Array[400 to 500], etc. The easiest way I could figure to do it (short of requiring the control IDs to be sequential) was to put the menu ID in the structs and loop the array to find it (Struct[i].MenuId).
-
No, what you propose is impossible in C. There are workarounds, but not exactly like you want.
It is possible to do what you want in C++, however (although not exactly Templates.VAR.Name).