It is my understanding that in \ifx\x\y xx \else yy \fi, \ifx does NOT expand its arguments. If you want \ifx to compare the expanded values of \x and \y, then we need to do the expansion ourselves before feeding them to \ifx:
\edef\xpndX{\x}
\edef\xpndY{\y}
\ifx\xpndX\xpndY xx \else yy \fi
as\edef does this expansion for us. This is frequently the case when \x and \y are the arguments in a macro so we really have no idea what kind of quantity they represent.
I was adapting a code snippet I found in user2478's answer to the TeX-SE question Why does this simple \ifx test fail? and came up with the following MWE:
\documentclass{article}
\usepackage[svgnames]{xcolor} % to get named colors
\begin{document}
\chardef\mysteryletter=`H
% loop through A-Z to find out the mystery letter
\newcount\currentchar
\currentchar=`A
\loop
\chardef\temp=\the\currentchar
\edef\tmp{\temp}%
\ifx\mysteryletter\temp {\color{Red}\bf\temp}\else\temp\fi
\advance \currentchar by 1
\unless\ifnum \currentchar>90
\repeat
\end{document}
which, when compiled, generated the output:
which actually is the desired output, but it should NOT have been! I added the statement \edef\tmp{\temp} to get the 'expanded' version of \temp intending to change the \temp argument to the \ifx command to \tmp but had not when this document was compiled. Lo and behold, the desired result was printed out! This lead me to believe that the expansion performed by the \edef\tmp{\temp} statement was not required, so it was commented out and the document recompiled. This gave the wrong result; the letter H was not bold or red
I note that removing the comment character from the end of the \edef command had the expected affect of adding a space between each letter, but did not prevent the 'H' from being found and highlighted.
So my question is this: How does the unused expansion of \temp by the \edef statement change the comparison performed by the \ifx command? What am I missing here?


\chardef\temp=\the\currentcharshould always be\chardef\temp=\currentchar. There's no point in using\the(besides the desire of seeing your code break loose). – egreg Apr 28 '19 at 11:14