Search code examples
recursioninfinite-looppascal

Why is this recursive Pascal procedure not being caught in an infinite loop?


I wonder why the following recursive Pascal procedure actually terminates:

procedure reverseWordRecursive;

  var
  word : char;

begin
  read(word);
  if word = '.' then
    writeln
  else
    begin
      reverseWordRecursive;
      write(word)
    end;
end; {reverseWordRecursive}

The procedure acts differently as the code might suggest. When you run the code the call of read(word) only runs once in the beginning of the procedure. The user is not asked to input one single char at the beginning of each recursive call, but you rather input the whole string of char.

Why is it not being caught in an infinite loop at the "read(word)" call? Should it not ask the user to input a word for ever?

How does the procedure know to actually use the respective next character for each recursive call?


Solution

  • The Read() procedure, when used to read the standard input, stores all typed characters into a buffer including the entry terminating CR/LF (Enter).

    The value returned by Read() is according to the type of the argument passed to Read(). For example, if the argument is a string, then all characters except the terminating CR/LF are returned (ReadLn() would return also CR/LF). If the variable is a Char then one character is returned, and the rest of the entered characters remain in the buffer, and can be read later by calling Read() again.

    So, in your code, the read procedure reads standard input into a buffer until Enter is hit.

    Let's say you enter A, B, C and . followed by Enter.

    At this point, since the parameter is a char the first entered character 'A' is returned to your code.

    The char is evaluated, and if not '.' the procedure is called recursively. Now, there are chars in the input buffer, so the next character, 'B' is read from the buffer. The same for 'C' and then finally the '.'.

    This terminates the recursive calls, and starts to unwind the stack, which happens in reversed order, C, B and A.