一个变量的值传递给宏用C [英] Passing the value of a variable to macro in C

查看:622
本文介绍了一个变量的值传递给宏用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个变量的值传递给在C宏,但我不知道这是可能的。例如:

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;
}

在这里,我试图使用宏来的值分配给所有X_变量,使用 ## 标记。我知道我可以很容易地使用数组实现这一点,但是这仅仅是为了学习的目的。

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(我)被替换为,而不是 X1 (如果我== 1)。我知道定义和宏是如何工作的,这是所有关于替代,但我想知道是否有可能以信 I 通过i的值而不是宏。

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.

推荐答案

替换 i的值进入宏是不可能的,因为宏替换您的$ C $之前发生C语言是编译。如果你使用的GCC,你可以通过添加-E命令行参数见pre-处理器输出(但是要注意,你会看到所有的#包括插入到您的code)。

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是一种静态语言,你不能在运行时决定符号名。但是,如果你使用一个数组,并指使用标元素你想达到什么是可能的。作为一个经验法则,如果你有一个像X0,X1等许多变量,你应该使用一个容器象一个数组。

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.

这篇关于一个变量的值传递给宏用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆