Your second code is equivalent to
\def\comparenum[#1,#2]{ \def\x{#1} \def\y{#1} \ifnum\x=\y1 \else0 \fi}
(because spaces and end-of-lines are ignored after a control word). Now you should be able to see the main problem with the code. When TeX evaluates the conditional, it needs two numbers and does full expansion until finding tokens that cannot be interpreted as digits.
So it expands \x
and =
stops the search for digits while also starting the lookup for the next number; \y
is expanded and 1
follows. So the call \comparenum[1,1]
translates into
\ifnum1=11 \else0 \fi
which of course returns false.
You solve the issue with
\def\comparenum[#1,#2]{%
\def\x{#1}%
\def\y{#1}%
\ifnum\x=\y\relax
1%
\else
0%
\fi
}
The \relax
token stops the lookup for digits.
On the other hand, this construct is not expandable. You can make an expandable version with
\def\comparenum[#1,#2]{%
\ifnum#1=#2\space
1%
\else
0%
\fi
}
The \space
expands to a space token that stops \ifnum
from looking up for more digits and is then ignored by rule. However, this would leave a space if used with a counter register. A safer version would be
\def\comparenum[#1,#2]{%
\ifnum#1=\expandafter\id\expandafter{\number#2}\space
1%
\else
0%
\fi
}
\def\id#1{#1}
An e-TeX version would be simpler:
\def\comparenum[#1,#2]{%
\ifnum#1=\numexpr#2\relax
1%
\else
0%
\fi
}
Please, note the %
that protect the end-of-lines avoiding that they make spaces in the output.
etoolbox
and its\ifnumequal
test. Together with\ifboolexpr
you can easily nest stuff. But you can also look intoexpl3
and its vast array of tests.\comparenum[1,2]
.\def\x{#1} \def\y{#1}
could explain that ;-) But I'm wondering why the\def
's are needed at all...\ifnum#1=#2
should do more or less the same.1
and0
as "return" values you should try\ifnum\x=\y\relax