Passing a variable value to a macro in C

I am trying to pass the value of a variable to a macro in C, but I do not 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 am trying to use a macro to assign a value to all x_ variables using ## tokens. I know that I can easily achieve this with arrays, but this is for educational purposes only.

CONCVAR(i) is replaced by xi , not x1 (if i == 1). I know how a macro defines and works, all about substitution, but I want to know if I can pass the value i instead of the letter i to the macro.

+6
c c-preprocessor
source share
3 answers

Substituting the value of i in the macro is not possible, since macro replacements occur before your code compiles. If you use GCC, you can see the result in front of the processor by adding the command line argument '-E' (note that you will see all #include inserted into your code.)

C is a static language, and you cannot define symbol names at run time. However, what you are trying to achieve is possible if you use an array and reference elements using indexes. Generally, if you have a lot of variables like x0, x1, etc., you should probably use a container like an array.

+13
source share

No, because the value i exists only at runtime. Macro expansion occurs at compile time.

+9
source share

No, that will not work. The C / C ++ preprocessor is just a “text time processor”. Thus, it works with text found as it is in your source code.

That's why it takes the literal text "i", passes it to your macro, expanding it into the literal text "xi" in the source code. This is then passed to the compiler. The compiler then parses the text processed by the post-processing, and detects the letter token "xi" as an undeclared variable, moving up to the process.

You can take the source code of the sample and pass it to the gcc compiler (for example, I used gcc under cygwin, pasting your code into a file that I named pimp.c, due to the lack of a better name). Then you 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 this. To be able to do just that, the preprocessor had to act as an interpreter. C and C ++ are (usually) non-interpretable languages, and the preprocessor is not an interpreter. My suggestion was to clearly understand the differences between compilers and translators (and between compiled and interpreted languages).

Sincerely.

+1
source share

All Articles