[texhax] How to test for existence of a macro?

Neal H. Walfield neal at walfield.org
Sat Aug 29 11:20:49 CEST 2009


At Fri, 28 Aug 2009 18:14:48 -0600,
D. R. Evans wrote:
> I couldn't find this in the TeXbook, but perhaps I was just looking in the
> wrong place.
> 
> How should I test cleanly for the existence of a particular macro?

The secret is how \csname ... \endcsname acts when the specified
control sequence is not defined: if the resulting control sequence
token was not previously defined, the resulting control sequence acts
like \relax.  We can combine this with \ifx, which compares the value
of two marcos, as follows:

  % Prints `not defined'.
  \expandafter\ifx\csname foo\endcsname \relax not defined \else defined \fi
  
  \def\foo{}
  % Prints `defined'.
  \expandafter\ifx\csname foo\endcsname \relax not defined \else defined \fi

We need to use \expandafter as \ifx does not expand its arguments and
we want the expansion of the \csname ...\endcsname sequence.

Neal


More information about the texhax mailing list