What is double evaluation and why should it be avoided?

前端 未结 4 1875
情歌与酒
情歌与酒 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:04

    Consider the following expression:

     x = max(Foo(), Bar());
    

    Where Foo and Bar are like this:

    int Foo()
    {
        // do some complicated code that takes a long time
        return result;
    }
    
    int Bar()
    {
       global_var++;
       return global_var;
    }
    

    Then in the original max expression is expanded like:

     Foo() > Bar() ? Foo() : Bar();
    

    In either case, Foo or Bar is going to executed twice. Thereby taking longer than necessary or changing the program state more than the expected number of times. In my simple Bar example, it doesn't return the same value consistently.

提交回复
热议问题