What is double evaluation and why should it be avoided?

前端 未结 4 1864
情歌与酒
情歌与酒 2020-12-09 01:27

I was reading that in C++ using macros like

#define max(a,b) (a > b ? a : b)

can result in a \'double evaluation\'. Can someone give me

4条回答
  •  时光取名叫无心
    2020-12-09 02:06

    a and b occur two times in the macro definition. So if you use it with arguments that have side-effects, the side-effects are executed two times.

    max(++i, 4);
    

    will return 6 if i = 4 before the call. As it is not the expected behavior, you should prefer inline functions to replace such macros like max.

提交回复
热议问题