Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>So am I right in saying that if n=11111, 5 sum variables are created and pushed on the stack with each recursion?</p> </blockquote> <p>Conceptually, but compilers may turn some forms of recursion into jumps/loops. E.g. a compiler that does tail call optimization may turn</p> <pre><code>void rec(int i) { if (i &gt; 0) { printf("Hello, level %d!\n", i); rec(i - 1); } } </code></pre> <p>into the equivalent of</p> <pre><code>void loop(int i) { for (; i &gt; 0; i--) printf("Hello, level %d!\n", i); } </code></pre> <p>because the recursive call is in <em>tail position</em>: when the call is made, the current invocation of <code>rec</code> has no more work to do except a <code>return</code> to its caller, so it might as well reuse its stack frame for the next recursive call.</p> <blockquote> <p>If this is correct then what is the benefit of using recursion when I can do it in normal function using loops, thus overwriting only one memory location? If I use pointers, recursion will probably take similar memory as a normal function.</p> </blockquote> <p>For this problem, recursion is a pretty bad fit, at least in C, because a loop is much more readable. There are problems, however, where recursion is easier to understand. Algorithms on tree structures are the prime example.</p> <p>(Although every recursion can be emulated by a loop with an explicit stack, and then stack overflows can be more easily caught and handled.)</p> <p>I don't understand the remark about pointers.</p> <blockquote> <p>I don't see how the recursions (other than the last one which returns 0) return values without uncommenting line 3.</p> </blockquote> <p>By chance. The program exhibits undefined behavior, so it may do anything, even return the correct answer.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload