Why the following function is called thrice

后端 未结 6 1318
轻奢々
轻奢々 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:43

    Because macro: MAX(x, increment()) expands as:

    ( (x) > (increment()) ? (x) : (increment()) )
    

    Similarly next call of macro expands.

    Variable i is static so initially initialized with i = 42, and its incremented value persists in different function calls.

    below a sequence of function call shown with values of i returned by increment() function.

     increment();    i = 47, First call
    
       x      52       x     i       
    ( (50) > (52) ? (50) : (52) ) 
            Second        // ^ not called because condition is True 50 > 52
    

    second time:

        increment();   i = 57, Third call
    
         x      i       x      i         
      ( (50) > (62) ? (50) : (67) ) 
              Forth          Fifth   // called because condition is False  50 > 62
    

    This sequence is according to your output.

    Important to note you may be different output with different compilers because the order of evaluation of function arguments are undefined of Undefined behavior.

    http://www.stroustrup.com/bs_faq2.html#macro

提交回复
热议问题