# \iffmode fails for first token in matrix cells [duplicate]

\iffmode seems to fail for the first token in every matrix cell. Here is a minimal working example.

\documentclass[margin=5mm]{standalone}
\usepackage{mathtools}

\newcommand{\foo}{%
\ifmmode A%
\else B%
\fi%
}

\begin{document}
\foo\foo\foo\
$\begin{matrix} \foo\foo\foo& x\foo\\ \foo&x\\ \end{matrix}$
\end{document}


What I expect it to output is this

Yet, it outputs this

How should I solve this problem?

• This is known, use \relax\ifmmode instead. – Skillmon Aug 16 '19 at 15:49
• Is this for academic interest or for a real use case? If the latter, please add the intended code. Anyway, the braces around A and B are wrong. Not in the sense they produce errors, but because conditional don’t take braced arguments. – egreg Aug 16 '19 at 15:56
• @egreg, you're right, the braces in the MWE are useless (removed now). They were necessary in my original code, though. Anyway, problem solved. Thanks :) – Τίμων Aug 16 '19 at 16:10