[Tex/LaTex] How to compare integers in TeX

conditionalstex-core

I do not understand how I can compare integers in TeX.

\documentclass[]{article}    
\begin{document}

\if 1<>0
1 is not equal 0.
\else
1 equals 0.
\fi

\end{document}

According to this code snippet 1 equals 0. Why? I have read that integer comparisons are done with \ifnum, but this command throws errors.

Best Answer

\if compares two tokens, independently of what they mean. The test \if 1<>0 compares 1 and < and yields false, thus you see 1 equals 0. For the sake of the example, if you had, \if 11<>0 then the test would be true because TeX would compare 1 and the next 1 and would return true. Then the test:

\if 11<>0
11 is not equal 0.
\else
11 equals 0.
\fi

would print:

<>0 11 is not equal 0.

because the tokens <>0 would not be used by \if, so TeX would simply write them on the output.

To do an integer comparison you need \ifnum:

\ifnum 1=0
1 equals 0.
\else
1 is not equal 0.
\fi

Also, TeX does not have a not equal to comparison. You can only compare with <, =, or >.

Related Question