Unexpected Result in Macro

后端 未结 2 1823
日久生厌
日久生厌 2020-12-12 06:13

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

相关标签:
2条回答
  • 2020-12-12 06:53

    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.

    0 讨论(0)
  • 2020-12-12 06:57

    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.

    0 讨论(0)
提交回复
热议问题