I'm trying to pass the value of a variable to a macro in C, but I don't know if this is possible. Example:
#include <stdio.h>
#define CONCVAR(_n) x ## _n
int main () {
int x0, x1, x2, x3, x4, x5, x6, x7, x8, x9;
int i;
for (i = 0; i <= 9; i++) CONCVAR(i) = i*5;
return 0;
}
Here, I'm trying to use a macro to assign a value to all x_ variables, using ##
tokens. I know I can easily achieve this with arrays, but this is for learning purposes only.
CONCVAR(i)
is substituted to xi
, not x1
(if i == 1). I know how defines and macro work, it's all about substitution, but I want to know if it is possible to pass the value of i instead the letter i
to a macro.
Substituting the value of i
into the macro is impossible, since macro substitutions happen before your code is compiled. If you're using GCC, you can see the pre-processor output by adding the '-E' command line argument (Note however, that you'll see all the #include's inserted in your code.)
C is a static language and you can not decide symbol names at runtime. However, what you're trying to achieve is possible if you use an array and refer to elements using subscripts. As a rule of thumb, if you have many variables like x0, x1, etc, you should probably be using a container like an array.
No, because the value of i
only exists at run-time. Macro expansion happens at compile-time.
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