# Problems with TeX scoping [duplicate]

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?

-

## marked as duplicate by John Kormylo, Werner, Andrew Swann, Thorsten, Adam LiterJun 18 '14 at 16:40

Could you please post a full MWE? – Jubobs Jun 18 '14 at 15:02

\newcount\itemno
\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
\ifnum\itemno=4\the\itemno\fi
5


Answer: The \itemno increments by 15.

-

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.

\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.

-
Or replace the % by a \relax? – Jubobs 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
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