Thread: Basic Recursion Problem

  1. #1
    Registered User
    Join Date
    Jan 2012

    Basic Recursion Problem

    I have a problem using the recursion.
    what is the difference between these 2 codes?

    void test(int i)
        if(i==5) return;
        cout<<"print\n";//why this part is accessed????

    suppose we have called it by test(1);
    in the above code why the cout<<"print\n" portion is accessed when i execute the progeam.
    i understand what recursion is.
    i believe this is called tail recursion.but i cant understand its behaviour.
    can you give me an idea on this?
    please explain the its behaviour.

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    i believe this is called tail recursion.
    Tail call == the recursive call is the last thing in the function.
    Your function: the last thing is the cout statement.
    So obviously the recursive call is not tail recursive.

    By the way, tail call optimization is an optimization, and therefore MUST NOT change the program behavior. Not executing the cout would quite obviously be a change in the behavior.
    All the buzzt!

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Nice, France
    You understand I suppose that if you see the cout or not depends on the argument of the function.

    Run this simple code, I think it reveals much of the behavior. This is caused because the recursion unwinds.
    #include <iostream>
    using namespace std;
    void test(int i)
        if(i==5) return;
       cout<<print <<i<<endl;
    int main () {
        return 0;
    Code - functions and small libraries I use

    It’s 2014 and I still use printf() for debugging.

    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic recursion question
    By benrogers in forum C Programming
    Replies: 8
    Last Post: 02-28-2011, 03:23 PM
  2. Replies: 5
    Last Post: 01-13-2011, 12:12 PM
  3. recursion problem
    By claudiat13 in forum C++ Programming
    Replies: 2
    Last Post: 05-05-2010, 10:26 PM
  4. Recursion problem
    By ramayana in forum C Programming
    Replies: 3
    Last Post: 11-13-2006, 11:54 PM
  5. basic recursion function question. typo in book?
    By navyzack in forum C Programming
    Replies: 6
    Last Post: 04-18-2005, 11:07 AM