title: Is this undefined behaviour in C ? If not predict the output logically
body: <p><strong>Code 1</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int f(int *a, int b) 
  {
    b = b - 1;
    if(b == 0) return 1;
    else {
      *a = *a+1;
  
      return *a + f(a, b);
    }
  }
  
  int main() {
    int X = 5;
    printf("%d\n",f(&amp;X, X));
  }
  </code></pre>
  
  <p>Consider this C code. The question here is to predict the output. Logically, I get 31 as ouput. (<a href="http://codepad.org/r3vsqx2J">Output on machine</a>)</p>
  
  <p>When I change the return statement to</p>
  
  <pre><code>return f(a, b) + *a;
  </code></pre>
  
  <p>I logically get 37. (<a href="http://codepad.org/yiqtBBqI">Output on machine</a>)</p>
  
  <p>One of my friends said that while computing the return statement in </p>
  
  <pre><code>return *a + f(a, b);
  </code></pre>
  
  <p>we compute the value of a while going depth of the tree, i.e. *a first computed then <code>f(a, b)</code> is called, whereas in  </p>
  
  <pre><code>return f(a,b) + *a;
  </code></pre>
  
  <p>It is resolved while returning back, i.e. <code>f(a, b)</code> is computed first then <code>*a</code> is called.</p>
  
  <p>With this approach, I tried predicting the output of the following code myself:</p>
  
  <p><strong>Code 2</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int foo(int n) 
  {
      static int r;
      if(n &lt;= 1)
          return 1;
  
      r = n + r;
      return r + foo(n - 2);
  } 
  
  int main () {
     printf("value : %d",foo(5));
  }
  </code></pre>
  
  <p>For <code>return(r+foo(n-2));</code></p>
  
  <p><a href="https://i.stack.imgur.com/f72Ut.jpg"><img src="https://i.stack.imgur.com/f72Ut.jpg" alt="enter image description here"></a></p>
  
  <p>Im getting 14 as Output Logically (<a href="http://codepad.org/bopzQRVG#output">Output on machine</a>)</p>
  
  <p>For <code>return(foo(n-2)+r);</code></p>
  
  <p><a href="https://i.stack.imgur.com/QknCe.jpg"><img src="https://i.stack.imgur.com/QknCe.jpg" alt="enter image description here"></a></p>
  
  <p>I get 17 as output. (<a href="http://codepad.org/Z8FIuy8O">Output on machine</a>)</p>
  
  <p>However, when I run the code on my system I get 17 in both cases.</p>
  
  <p><strong>My Questions:</strong></p>
  
  <ul>
  <li>Is the approach given by my friend correct?</li>
  <li>If so, why do I get the same output in <strong>Code 2</strong> when I run in a machine?</li>
  <li>If not, what is the correct way to interpret <strong>Code 1</strong> and <strong>Code 2?</strong></li>
  <li>Is there any undefined behaviour because C does not support pass by Reference? As it is being used in <strong>Code 1</strong> tough it can be implemented using pointers?   </li>
  </ul>
  
  <p>In a nutshell, I simply wanted to know the correct way to predict the output in the 4 cases mentioned above.</p>