开发者

Difference between using a macro and its expansion

#define ADD(a,b) (a)+(b)

void foo1()
{
    int a=1, b=2;
    int k=0;
    while(k++ < 10000)
    {
        int c = ADD(a,b);
        a = c;
    }
}

void foo2()
{
    int a=1, b=2;
    int k=0;
    while(k++ < 10000)
    {
        int c = a + b;
        a = c;
    }
}

what is the difference between foo1 and foo2. Someone asked me this question and 开发者_Python百科I could not find any difference. both seem 100% same. Maybe some difference regarding memory allocation on stack? you may try to answer the question with the assumption that memory is very limited?


The only difference has to do with the fact that instead of writing the macro as you did, you need to enclose the whole macro in an additional set of parens:

#define ADD(a,b) ((a)+(b))

If you do not make that fix, then

ADD(3,4) * 5

equals 23, but

(3 + 4) * 5

equals 34.

It's great that you did correctly enclose each macro parameter in its own parens, but you also need to enclose the entire macro in parens to avoid precendence-related mistakes.


As far as i know, this is exactly the same.

The macro gets expanded in the preprocessor, than it gets compiled. So the net result is exactly the same, both in processing and memory costs.

The only difference being that preprocessing may take a little more time. (Though negligible)


Like they said, but there is a difference in that ADD(5, 5) * 5 would be assumed to evaluate to 50 whereas 5 + 5 * 5 would be assumed to be evaluated to 30. In fact, as you have defined them, both would be 30 so be sure to add the extra parentheses in your definition: #define ADD(a,b) ((a)+(b))


There is no difference, the preprocessor runs before the code is compiled and just does a dumb replacement.


As far as the C compiler is involved, there is just a tiny little less work for it to do.

One of the steps in compiling source files is the preprocessing. One of the steps of preprocessing is expanding the macro.

When you expand the macro by hand, the compiler doesn't have to do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜