Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

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?

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.

Following is my present code

#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"); 

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.

Upvotes: 4

Views: 2440

Answers (2)

H Walters
H Walters

Reputation: 2654

Is it possible to perform arithmetic (multiplication for my case) using macros?

Yes, given the restrictions you specified (that you're using constants; in particular, decimal literals), and with restrictions. The linked to code shows an ADD and a MUL macro that does just this (it's a bit too big to just paste inline). To do this with a preprocessor macro per se requires "implementing arithmetic". This example only supports numbers from 1 to 255, and requires your C99 compliant preprocessor support 511 arguments.

The Boost preprocessor library also contains an implementation of macro arithmetic; and has code supporting DIV and SUB.

Upvotes: 2

Jens
Jens

Reputation: 72639

No. The C preprocessor operates purely on tokens (by replacing one token sequence with another). It does not do arithmetic in between.

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?

Upvotes: 5

Related Questions