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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With