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
#define CONCVAR(_n) x
No, it won't work. The C/C++ pre-processor is just that, a "pre-compile" time text processor. As such, it operates on the text found as-is in your source code.
That's why, it takes the literal text "i", pass it into your macro, expanding that into the literal text "xi" in your source code. Then that gets passed into the compiler. The compiler then starts parsing the post-processed text, finding the literal token "xi" as an undeclared variable, going belly up in the process.
You can take your sample source code and pass it to a gcc compiler (I used gcc under cygwin for example, pasting your code into a file I named pimp.c for lack of a better name). Then you'll get the following:
$ gcc pimp.c
pimp.c: In function `main':
pimp.c:9: error: `xi' undeclared (first use in this function)
pimp.c:9: error: (Each undeclared identifier is reported only once
pimp.c:9: error: for each function it appears in.)
In short, no, you cannot do that. To be able to do just that, then the pre-processor would have to act as an interpreter. C and C++ are (generally) not interpreted languages, and the pre-processor is not an interpreter. My suggestion would be to get very clear on the differences between compilers and interpreters (and between compiled and interpreted languages.)
Regards.
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.