3

If I use

\global\advance\itemno by 1%
\ifnum\itemno=4\the\itemno\fi

I get 5. If I use

\global\advance\itemno by 1%
\itemno=\itemno%
\ifnum\itemno=4\the\itemno\fi

I get 4 as expected. Why is this necessary?

John Kormylo
  • 79,712
  • 3
  • 50
  • 120

2 Answers2

6

You need an inverse egreg: don't put % at ends of lines.

\global\advance\itemno by 1
\ifnum\itemno=4 \the\itemno\fi

Otherwise the \ifnum is expanded while looking for the end of the number that starts with 1 before the assignment is done.

In addition,

\ifnum\itemno=4\the\itemno\fi

can never be true as if \itemno is say 4 then it is equivalent to

\ifnum\itemno=44\fi

which will of course be false. hence the space after 4 in the above.

David Carlisle
  • 757,742
  • Or replace the % by a \relax? – jub0bs Jun 18 '14 at 15:13
  • @Jubobs If you like typing (and you are not in an expandable context where \relax will mess you up) – David Carlisle Jun 18 '14 at 15:15
  • 2
    From the TeXbook, p. 208: For best results, always put a blank space after a numeric constant; this blank space tells TeX that the constant is complete, and such a space will never “get through” to the output. – egreg Jun 18 '14 at 15:17
3

Your first example

\newcount\itemno
\global\advance\itemno by 1%
\ifnum\itemno=4\the\itemno\fi

is interpreted by TeX: \global\advance\itemno by 1...

the \ifnum is expanded because the number scanning is not finished: \ifnum\itemno=4... the \the\itemno is expanded to 0, so \ifnum\itemno=40\fi. because \itemno isn't 40 then \ifnum expands to empty, so \global\advance\itemno by 1<empty> is executed now, it means the \itemno increments. And that is all. IMHO this was not the intention of the author. The second example is similar.

Exercise: what hapens when you type:

\newcount\itemno
\global\advance\itemno by 1%
\ifnum\itemno=4\the\itemno\fi
5

Answer: The \itemno increments by 15.

wipet
  • 74,238