What problems might the following macro bring to the application?

前端 未结 6 2050
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 02:50

Can the following macro bring problems?

#define sq(x) x*x

If yes, then how and why?please help.

6条回答
  •  执念已碎
    2021-01-27 03:36

    Yes, it can present problems. Other than the obvious fact that macros don't respect namespaces at all (which means you can't call anything else sq), try the following:

    int result = sq(4) / sq(4);
    

    You should surround x * x with parenthesis so it becomes ((x) * (x)).

    Another problem:

    int a = 0;
    int result = sq(++a);
    

    This is an inherent problem with macros, and is one reason inline functions should be preferred.

提交回复
热议问题