Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to generate variable names at compile time in C/C++?

Tags:

c++

c

With reference to the SO thread C Macro Token Concatenation involving a variable - is it possible?,

Is it at all possible to generate variable names at compile-time in C and C++?

something like

int count = 8;
for(i=0; i<count; i++) {
    int var_%i% = i*i;   // <--- magic here
}

I know I can use arrays for this case, but this is just an example just to explain what I mean.

like image 648
Lazer Avatar asked Dec 29 '22 07:12

Lazer


2 Answers

If you are expecting to use the value of i to generate the name var_%i% (e.g. generating variables var_1, var_2, ..., var_count), then no, that's not possible at all. For one thing, that's not even a compile-time operation. The value of i isn't known until runtime. Yes, you can tell what it will be (and maybe a compiler could with static analysis in a very simple case), but in general values are exclusively run-time concepts.

If you just mean creating a variable called var_i, why don't you just name it that?

Maybe it would help if you explained what problem you're trying to solve by doing this. I guarantee there's a better way to go about it.

like image 99
Tyler McHenry Avatar answered Dec 30 '22 20:12

Tyler McHenry


In C++, you can achieve things a bit like this with templates (but I'm no expert, so I'll say no more). Google for "template metaprogramming". However, this isn't based on variables (in the run-time sense).

In C, this cannot be done (well, certainly nothing close to your example).

like image 38
Oliver Charlesworth Avatar answered Dec 30 '22 20:12

Oliver Charlesworth