1

I have to create objects dynamically. So for that I have the following:

#define timerID(num) timerID_##num

This results in as timerID_num instead of say timerID_1. Can someone let me know how to do this?

Rndp13
  • 1,094
  • 1
  • 21
  • 35
jxgn
  • 741
  • 2
  • 15
  • 36
  • 1
    remove the semicolon and the ## – Zelldon Jun 09 '15 at 10:54
  • sorry about that `;` but removing ## I don't get what you mean? – jxgn Jun 09 '15 at 10:58
  • http://stackoverflow.com/q/10379691/812912 – Ivaylo Strandjev Jun 09 '15 at 10:59
  • 1
    Please re-consider your specification... there exist very few if any cases where you would need to "create variables dynamically". It is likely that there are better ways to solve the actual problem for which you need these "dynamic variables". – Lundin Jun 09 '15 at 11:08
  • @Lundin I have edited my question. Actually I need to create objects not variables. And I need to create dynamically variables of objects which I already created which I need to use when I dynamically create objects. – jxgn Jun 09 '15 at 11:31
  • There's no difference between an object (instance of class) or a variable. An object is always a variable. And listening to your strange spec, it seems arrays or other containers will solve everything. Still, the question is what's the actual problem being solved here? Whenever you find yourself coming up with the need for an unique feature that few, if any, programmers before you have needed, it is usually a sign of flawed program design. – Lundin Jun 09 '15 at 11:46
  • @Lundin Thanks for your response. I will use arrays instead. – jxgn Jun 09 '15 at 13:38

1 Answers1

1

Check following code snippet:

#define f(g,g2) g##g2

void main()
{
   int timerID_1 = 12;
   printf("%d",f(timerID_,1)); 
}

This will concatenate to timerID_1. I printed the value just for debug.

Amol Saindane
  • 1,568
  • 10
  • 19
  • This will obviously work. I need to pass like this `f(timerID_,num);` – jxgn Jun 09 '15 at 11:25
  • @XavierGeoffrey : This won't be possible as C is a static language and you can not decide symbol names at runtime. Please refer to this link which answers to your question : http://stackoverflow.com/questions/5018059/passing-the-value-of-a-variable-to-macro-in-c – Amol Saindane Jun 09 '15 at 11:45
  • Thanks. I will use array for my purpose. – jxgn Jun 09 '15 at 13:37