Unexpected Result in Macro

荒凉一梦 提交于 2019-12-02 18:12:39

问题


I have a simple program to calculate the volume of a cube. It runs fine, but the result I get is wrong. It comes out as "Y is 392". Can anyone help me understand why it is 392? I have just begun C, so I do not understand all of the code.

I realise this Macro is badly written, I am just trying to understand its behavior before I rewrite it.

#define CUBE(x) (x*x*x)

void main(void);

void main(void){
    int x, y;
    x = 5; 
    y = CUBE(++x);
    printf("Y is %d \n", y);
}

回答1:


This is because the macro expands to:

y = ++x * ++x * ++x;

This is a very badly written macro, for this very reason; it looks like a function call (which would evaluate the argument only once) but it really evaluates it three times.

This gives undefined behavior since there is a lack of sequence points.




回答2:


The reason this happens is that the macro pre-processor substitutes the parameters as they are. So, CUBE(++x) is expanded to:

++x*++x*++x

You should avoid using expressions with side effects in macros because of this.



来源:https://stackoverflow.com/questions/22640204/unexpected-result-in-macro

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