Passing the value of a variable to macro in C

不打扰是莪最后的温柔 提交于 2019-12-10 13:27:15

问题


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.


回答1:


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.




回答2:


No, because the value of i only exists at run-time. Macro expansion happens at compile-time.




回答3:


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.



来源:https://stackoverflow.com/questions/5018059/passing-the-value-of-a-variable-to-macro-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!