tags:

views:

124

answers:

3

In my textbook, there is this example very similar this to reverse a line from an input file:

void Reverse(ifstream &inFile, int level) 
{
    int myInput = inFile.get();
    if (myInput != '\n' && myInput != EOF) // don't understand this, line 4
        Reverse(inFile, level);
    if (myInput != EOF)
        cout.put(myInput);
}

What I don't get is the line I commented. Because from an input file that's inputs were:

ABC\n
DEF\0

When the \n is equal to myInput, doesn't it make line 4's conditional statement become false since the first (myInput != '\n') would be false, and the second part (myInput != EOF) be true making that whole line false, and not calling the Reverse function again? Thanks.

+1  A: 

That line is the recursion's base condition. Apparently, this function is designed to print out one line in reverse from the input file at a time. So, once it encounters a \n or an EOF, it has reached the end of the current line, and so does not continue further. Repeated calls to Reverse print out successive lines.

MAK
A: 

You're right. It won't call Reverse() when the character is a '\n'. So this will only reverse the first line of a file.

John
+1  A: 

The trick to understanding recursion on a very basic level is to trace the execution and write out the sequence of calls. The following might help you to understand how this works. I indented each call to Recurse() and included the line numbers that are executed.

3: myInput = 'A'
5: Reverse()
  3: myInput = 'B'
  5: Reverse()
    3: myInput = 'C'
    5: Recurse()
      3: myInput = '\n' <<<< base condition, recursion stops here
      7: cout.put('\n')
    7: cout.put('C')
  7: cout.put('B')
7: cout.put('A')

So this will output '\nCBA'.

As for the logic in the base condition, remember De Morgan's Laws:

(NOT P) AND (NOT Q)
    -> NOT (P OR Q)
(myInput != '\n') && (myInput != EOF)
    -> (!(myInput == '\n')) && (!(myInput == EOF))
    -> !((myInput == '\n') || (myInput == EOF))

The if statement on line 4 will exclude newlines and the end of file condition so the recursion stops when it encounters either condition. This is what causes the recursion to only read one line from the file.

D.Shawley