简体   繁体   中英

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 .

Actually I want to evaluate the expression with value n . So let's say if I pass value of n as 1 than I expect output 0x8020520 . Similarly if I pass value of n as 8 than I expect 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 . Any help will be appreciated.

When you do (0x8020##4+n) , it is parsed as these tokens: "(", "0x8020" ## "4", "+", "n", ")".

After pasting "0x8020" and "4" together, you end up with ( 0x80204 + n ) . This doesn't actually add n before pasting. (And how could it? The preprocessor doesn't know what a variable is, and it thinks "n" is just a 1-length string)

When you do ) ## 20 , you end up with the invalid token ")20", which doesn't make sense. So it rightfully throws an error.

It seems like you want to replace one hex digit with the value of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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