-1

I had read recently that recursion uses system stack for storing return addresses of function calls. So, I just made a random code to understand this LIFO concept in recursion

int fun( int x) 
  {  if ( x<6 || x>6 ) 
       { cout<<x; 
          return 0; 
        } 
      else 
       return max(fun(x-1),fun(x+1)); 
    } 
    int main(){ 
     cout<<fun(6); 
     return 0; 
  } 

I expect output

570

Actual output is

750

I was assuming function will call in this order-

fun(6)->fun(5) { it will print 5 then return 0} ->fun(7) { it print 7 then return 0} -> max(0,0) { return 0}

Correct me, where I am getting wrong.

T.g
  • 169
  • 2
  • 11
  • 6
    The order in which function arguments are evaluated is not specified. – tkausl Jun 25 '19 at 13:04
  • 1
    Try `int result1 = fun(x-1); int result2 = fun(x+1); return max(result1, result2);` – Kevin Jun 25 '19 at 13:07
  • I don't get it for what you are asking. – T.g Jun 25 '19 at 13:07
  • 1
    The order in which the arguments to a function are evaluated is implementation-defined; some compilers (apparently including yours) will evaluate them right-to-left rather than left-to-right. If you want to force a particular evaluation ordering, you can make your recursive calls separately and store their results into local variables, and then pass those local variables in to max() afterwards. – Jeremy Friesner Jun 25 '19 at 13:08
  • 1
    as a basic example, your example is far too complicated. Try something simpler, as `void countdown(int i) { if (i == 0) return; std::cout << i; countdown(i-1);}`. Then try to see what happens when you swap the order of the lines... – 463035818_is_not_an_ai Jun 25 '19 at 13:08

1 Answers1

3

In C++, the order of evaluation of arguments is unspecified.

When writing max(fun(x-1),fun(x+1)); the compiler is free to choose to evaluate fun(x+1) first.

gan_
  • 656
  • 5
  • 15
  • So, if according to you compiler is free to choose which argument should be evaluated. Then it means it will give different output if i will run it one more time. – T.g Jun 25 '19 at 13:13
  • 1
    @t.g no it just means that you have no guarantee which is first. A compiler could choose to always evaluate the first argument while another one might choose to start with the second – 463035818_is_not_an_ai Jun 25 '19 at 13:14
  • 4
    it means you should avoid this kind of code (that has unspecified behaviour). – bolov Jun 25 '19 at 13:15
  • ok, I just get it. That the code specified by me has undefined behavior. Moreover, the order of evaluation is compiler dependent. Thnks. – T.g Jun 25 '19 at 13:20