宏执行整数运算 [英] Macro perform integer arithmetic
问题描述
是否可以使用宏执行算术运算(对于我的情况是乘法)?
Is it possible to perform arithmetic (multiplication for my case) using macros?
据我所知,写一个宏像:
I understand that writing a macro like:
#define mult(a,b) ((a)*(b))
会到处替代产品.但是我两个参数都是常量.我知道,编译器也将静态执行乘法运算,但问题是,我使用#将结果转换为字符串.
Will substitute the product everywhere. But I have both my parameters as constants. I know the compiler will also perform the multiplication statically, but the issue is that I have to convert the result to a string using #.
有什么想法可以做到吗?
Any idea how it can be done?
此外,如果它能够与C ++宏来完成,我仍是好的.我可以写在C ++那些特定的模块和连接起来.
Also if it can be done with C++ macros, I am still okay. I can write those particular modules in C++ and link it up.
以下是我本代码
#define ARG_COPY() __asm__("subq $8, %rsp"); \
__asm__("movq %gs:0xe8, %r10"); \
__asm__("movq $16, %r11"); \
__asm__("1:"); \
__asm__("movq -8(%r10, %r11, 8), %rax"); \
__asm__("pushq %rax"); \
__asm__("decq %r11"); \
__asm__("jne 1b"); \
#define ARG_REMOVE() __asm__("add $136, %rsp");
现在上面的代码被写入没有参数 - 136是16×8 + 8.我想使该16的参数.相同的16设置在第一宏太使用.
Now the above code is written without arguments - the 136 is 16 * 8 + 8. I want to make that 16 a parameter. The same 16 is used in the first macro too.
推荐答案
没有. C预处理器仅对令牌进行操作(通过将一个令牌序列替换为另一令牌序列).两者之间不做算术运算.
No. The C preprocessor operates purely on tokens (by replacing one token sequence with another). It does not do arithmetic in between.
您必须编写自己的一种预处理的这一点.还是用产品字符串创建头文件,并在需要的地方包含#include呢?另一种可能性:不要打扰;如果不是真正的性能瓶颈,请使用sprintf(s, "%d", mult(a,b));
.也许某些编译器 足够聪明,可以在编译时对其进行评估.
You would have to write your own kind of preprocessor for this. Or what about creating header file with the product strings and #including it where needed? Yet another possibility: don't bother; if it's not truly a performance bottleneck, use sprintf(s, "%d", mult(a,b));
. Maybe some compiler is smart enough to evaluate this at compile time.
有多少产品不断的字符串,你呢?他们中有多少不同?
How many constant product strings do you have? How many of them are different?
这篇关于宏执行整数运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!