# Why does \loop behave differently depending on order of its contents?

Just a question out of curiosity. I tested the code below, and first two {\loop...\repeat} commands returned \TeX!\quad six times, and others returned it five times. Why do only first two {\loop...\repeat} commands return \A (= \TeX!\quad) six times? What difference is there between first two commands and remaining commands?

\documentclass{article}
\begin{document}
\makeatletter
\newcount\cnt@a
\def\C{\ifnum\cnt@a>0}
\cnt@a=5
{\loop\A\B\C\repeat}

{\loop\A\C\B\repeat}

{\loop\B\A\C\repeat}

{\loop\B\C\A\repeat}

{\loop\C\A\B\repeat}

{\loop\C\B\A\repeat}
\end{document}

• Welcome to TeX.SX! You can use back-ticks to highlight in-line code.
– user30471
Commented Aug 13, 2015 at 12:05

The definitions of \B and \C are the problem:

\def\B{\advance\cnt@a by-1}
\def\C{\ifnum\cnt@a>0}


TeX does not stop at the end of the numbers, but continue expanding until it finds a token, which is not a digit, e.g.:

\B1234\relax


will decrease \cnt@a by -11234, not by -1. Or

\B\C


Then the \ifnum is executed before the counter is decreased.

Both cases are fixed by appending a space after the number, which ends the number and is ignored for typesetting:

\def\B{\advance\cnt@a by-1 }
\def\C{\ifnum\cnt@a>0 }


Alternatively, the registers \m@ne or \z@ can be used:

\def\B{\advance\cnt@a by\m@ne}
\def\C{\ifnum\cnt@a>\z@}


Full example:

\documentclass{article}
\begin{document}
\makeatletter
\newcount\cnt@a
\def\C{\ifnum\cnt@a>0 }
\cnt@a=5
{\loop\A\B\C\repeat}

{\loop\A\C\B\repeat}

{\loop\B\A\C\repeat}

{\loop\B\C\A\repeat}

{\loop\C\A\B\repeat}

{\loop\C\B\A\repeat}
\end{document}