Strange behavior of Macro-expansion

≡放荡痞女 提交于 2020-02-10 16:01:46

问题


Here's the code:

#include <stdio.h>
#include <stdio.h>
#define VAL1(a,b)    a*b
#define VAL2(a,b)    a/b
#define VAL3(a,b)    ++a%b
int main()
{
    int a = 1;
    int b = 2;
    int c = 3;
    int d = 3;
    int e = 5;

    int result = VAL2(a,d)/VAL1(e,b)+VAL3(c,d);  // result = 1
    //int result = a/d/e*b+++c%d;                // result = 0

    printf("%d\n", result);

    return 0;
}

Why aren't the results of two statements the same?


回答1:


In one case you have + ++ and in the other case you have ++ +. + ++ and ++ + are different streams of tokens. Macro pasting doesn't change tokenization because it's tokens that are pasted.

If you punch your program into a C pre-processor, you'll get this out for that line:

int result = a/d/e*b+ ++c%d;

Notice that the preprocessor had to insert a space because one is mandatory between a + token and a ++ token.




回答2:


I tried to compile it with GCC 4.7, and the two expressions gave the same results.

If you want to see how macro will expand, you can use cpp, which is the C Preprossessor, and will give you the output after preprocessor expression are executed, here the output is

int main()
{
    int a = 1;
    int b = 2;
    int c = 3;
    int d = 3;
    int e = 5;

    int result = a/d/e*b+++c%d;  
    int result2 = a/d/e*b+++c%d;  

    printf("%d %d\n", result, result2);

    return 0;
}



回答3:


If you really think it is necessary to use such macros, you'll need to use parenthesis () to avoid side-effects:

#define VAL1(a,b)    ((a)*(b))
#define VAL2(a,b)    ((a)/(b))
#define VAL3(a,b)    ((++a)%(b))


来源:https://stackoverflow.com/questions/15337185/strange-behavior-of-macro-expansion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!