简体   繁体   English

如何使用##运算符连接和评估宏

[英]How to concatenate and evaluate macro using ## operator

I have written ac code like this 我已经写了这样的交流代码

#include<stdio.h>
#include<stdint.h>
#define CHAN(n) ((0x8020##4+n) ## 20)
void main()
{
     int n = any_value;
     printf("%x",CHAN(n));
}

I am getting compilation error pasting ")" and "20" does not give a valid preprocessing token . 我在pasting ")" and "20" does not give a valid preprocessing token时遇到编译错误, pasting ")" and "20" does not give a valid preprocessing token

Actually I want to evaluate the expression with value n . 实际上,我想评估值为n的表达式。 So let's say if I pass value of n as 1 than I expect output 0x8020520 . 因此,假设我将n值传递为1不是期望输出0x8020520 Similarly if I pass value of n as 8 than I expect 0x8020c20 . 类似地,如果我将n值传递为8 ,则我期望0x8020c20

If I remove ##20 from the macro than I don't get any compilation error and i get expected half output like 0x80205 or 0x8020c My problem is I am not able to find a way to concatenate 20 after expression evaluation ie (0x8020##4+n)##20 . 如果我从宏中删除##20 ,则没有得到任何编译错误,并且得到预期的一半输出,如0x802050x8020c我的问题是我无法找到一种在表达式求值后将20连接的方法,即(0x8020##4+n)##20 Any help will be appreciated. 任何帮助将不胜感激。

When you do (0x8020##4+n) , it is parsed as these tokens: "(", "0x8020" ## "4", "+", "n", ")". 当您执行(0x8020##4+n) ,它将被解析为以下标记:“(”,“ 0x8020” ##“ 4”,“ +”,“ n”,“)”。

After pasting "0x8020" and "4" together, you end up with ( 0x80204 + n ) . 将“ 0x8020”和“ 4”粘贴在一起后,您将得到( 0x80204 + n ) This doesn't actually add n before pasting. 粘贴前实际上并没有添加n (And how could it? The preprocessor doesn't know what a variable is, and it thinks "n" is just a 1-length string) (怎么可能?预处理器不知道变量是什么,它认为“ n”只是一个长度为1的字符串)

When you do ) ## 20 , you end up with the invalid token ")20", which doesn't make sense. 当您执行) ## 20 ,您将得到无效的令牌“)20”,这是没有意义的。 So it rightfully throws an error. 因此,它理应引发错误。

It seems like you want to replace one hex digit with the value of n . 似乎您想用n的值替换一个十六进制数字。 You can easily do this with bitwise operations: 您可以通过按位操作轻松地做到这一点:

 #define CHAN(n) (0x8020020 | ((4 + n) << 8))
 //                     ^

(Where the shift moves the single hex digit represented by (4 + n) to the second place value, and | (bitwise or)-ing it will replace the indicated 0. (当移位将由(4 + n)表示的单个十六进制数字移动到第二位的值时, | (按位或)对它将替换指示的0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM