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

前端 未结 4 778
半阙折子戏
半阙折子戏 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:23

    Because you are using undefined behaviour. When the macro is expanded, your code turns into this:

    std::cout<<++p*++p;
    

    using increment/decrement operators on the same variable multiple times in the same statement is undefined behaviour.

提交回复
热议问题