[Tex/LaTex] Infinite loops in TeX

macrostex-core

Some day I will learn how TeX actually works; in the meantime I ask here ;-)

The code

\def\x{Hello!\par\x}
\x

gets stuck in an infinite loop, producing some thousands pages in a few seconds (as I expected). On the other hand, the snippet

\def\x{Hello!\x}
\x

results in the error

! TeX capacity exceeded, sorry [main memory size=5000000].
\x ->Hello 
          !\x

I would like to understand this behaviour. If I think just about macro expansion, I expect an infinite loop also in the latter situation: obviously this is not true, and issuing a new paragraph influences things.

Best Answer

When TeX sees \par, it makes a paragraph, building lines of text; when a sufficient number of lines is reached, it ejects a page and removes it from its memory. So it never runs out of memory with the first loop.

In the second case, it continues storing tokens until a paragraph ends. Which doesn't happen, obviously, before memory is exhausted.

It's important to note that when a macro is expanded, it is replaced by its replacement text and the original token disappears. However, the tokens Hello! are in both cases sent to the internal processor for building boxes.