#define SQR(x) x*x. Unexpected Answer

前端 未结 4 776
半阙折子戏
半阙折子戏 2020-12-12 07:34

Why this macro gives output 144, instead of 121?

#include
#define SQR(x) x*x

int main()
{
    int p=10;
    std::cout<         


        
4条回答
  •  离开以前
    2020-12-12 08:20

    Because SQR(++p) expands to ++p*++p, which has undefined behavior in C/C++. In this case it incremented p twice before evaluating the multiplication. But you can't rely on that. It might be 121 (or even 42) with a different C/C++ compiler.

提交回复
热议问题