Why the following function is called thrice

后端 未结 6 1271
轻奢々
轻奢々 2021-01-20 10:45

I had tried to debug but no luck I can\'t understand why the second printf() is call increment() thrice but the first one call twice as expected.

#include &l         


        
6条回答
  •  臣服心动
    2021-01-20 11:33

    This is a classic example of side effects in macros. Your max macro examples out to this:

    x > increment() ? x : increment()
    

    Once the return value from increment() if bigger than x the ternary operator will call increment() twice, once to evaluate the condition and once to evaluate the false part (which is the second increment()).

    In this case you're best best is to max max_int function:

    int max_int(int a, int b)
    {
      return a > b ? a : b;
    }
    

    Calling this instead of MAX will ensure your arguments are only ever evaluated once.

提交回复
热议问题