Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by John Kormylo, Werner, Andrew Swann, Thorsten, Adam Liter Jun 18 at 16:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer

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.

share|improve this answer
    
Or replace the % by a \relax? –  Jubobs Jun 18 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 at 15:15
1  
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 at 15:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.