# Why is it recommended to put \relax before \ifmmode?

I've several times seen the recommendation to put a \relax before \ifmmode in a macro. I've tried searching for an explanation of this several times on this site, but hadn't been able to find one. An answer by David Carlisle to a different question I asked suddenly made things click, and I thought it'd be worthwhile to submit a question that might help others more effectively find the explanation of this.

• It's a nice effort, but I think that there can't be said more than in tex.stackexchange.com/questions/27592/… , which makes it a dupe IMHO... – yo' Aug 20 '14 at 13:24
• Sure, I'm happy for the question be closed as a dupe, if it will still show up in searches and point others to the fuller answers. I considered suggesting that myself. – dubiousjim Aug 20 '14 at 13:26

In short, the explanation is that in several contexts:

\def\foo{\ifmmode alpha\else beta\fi}
...$\foo ...$ ...


it won't yet be visible that we're in math mode when \foo is invoked. But after \relax, then \ifmmode will then be able to see that we are in math mode.

Knowing the explanation, I was then able to find these further discussions of it on this site:

But these weren't easy to find until I did know the explanation.

For further discussion, one should consult Chapter 22 of The TeX Book, esp. p. 238.

• note that \relax solves the problem of math mode at start of alignment but can cause problems in the non math case (as it breaks ligatures and kerning) and still fails in \write so a protected definition is usually preferable. – David Carlisle Aug 20 '14 at 14:39