I have this code with nested ifx (plain TeX):
\def\test#1#2%
{
\edef\cmpa{#1}
\edef\cmpb{x}
\ifx\cmpa\cmpb
it is x
\edef\cmpa{#2}
\edef\cmpb{1}
\ifx\cmpa\cmpb
and 1
\else
and something else
\fi
\else
it is something else
\fi
}
\test{x}{1} % prints: it is x and 1
\test{x}{2} % prints: it is x and something else
\test{y}{1} % prints: it is something else
It works fine but is much code in \test for what it is doing.
I tried to tidy this like:
\def\ifEq#1#2%
{
\edef\cmpa{#1}
\edef\cmpb{#2}
\ifx\cmpa\cmpb%
}
\def\test#1#2%
{
\ifEq{#1}{x}%
it is x
\ifEq{#2}{1}%
and 1
\else
and something else
\fi
\else
it is something else
\fi
}
\test{x}{1} % prints: it is x and 1
\test{x}{2} % prints: it is x and something else
\test{y}{1} % -> error
The code of \test is much easier, but it produces an error for y:
! Extra \else.
\test ...and 1 \else and something else \fi \else
it is something else \fi
l.54 \test{y}{1}
Why does the first work but not the second one?
(I have to notice, that the parameters for \test and the tested texts can be longer texts, not only one letter; parameters for \test can be macros)
Thanks, Peter
Edit:
Thank you all for your answers! The most important hint is this: „TeX does not expand macros when searching for \else or \fi in false case.“ The solution in the accepted answer seems to be the easiest and smartest :-)
Edit 2: (please ignore, was nonsense)
I just see, i cannot do an if .. else .. if like this:
\def\Eq#1#2%
{%
TT\fi%
\edef\cmpa{#1}%
\edef\cmpb{#2}%
\ifx\cmpa\cmpb%
}
\def\test#1#2%
{
\if\Eq{#1}{x}%
it is x
\if\Eq{#2}{1}%
and 1
\else
and something else
\fi
\else
\if\Eq{#1}{y}%
it is y
\if\Eq{#2}{1}%
and 1
\else
and something else
\fi
\fi
}
An error is thrown by \test{x}{1} deep inside the following code of my project. Seems there is an if unclosed now.

\elseor\fi. Therefore the\ifxin the second\ifEqis not found and the first\elseis already interpreted as corresponding to the\ifxof the first\ifEq. So you should not expand a macro to a TeX conditional like\iftrue,\iffalse,\if,\ifx,\ifcase. I'm almost sure, there are already questions about this. – cabohah Mar 07 '24 at 10:11\fiat the end (4\if, 3\fi) – David Carlisle Mar 07 '24 at 12:12