What problems might the following macro bring to the application?

前端 未结 6 2044
伪装坚强ぢ
伪装坚强ぢ 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:31

    As pointed out, you should wrap each use of the argument in parentheses to ensure correct behavior, for example, when the argument is something like i * 2:

    #define sq(x) ((x)*(x))
    

    But there is another potential issue. Consider the following:

    result = sq(++i);
    

    This is translated to:

    result = ((++i)*(++i))
    

    Where as the intention was likely to increment i only once, it gets incremented twice. This is a common side effect for macros.

    One approach is just to be aware of this when calling it, but a better one is to put sq() in its own inline function.

提交回复
热议问题