17

I've run into this issue several times now, and have just worked around it in other ways. But it would be simpler just to know how to do it properly.

I would like to use \ifdefined in the context of a macro that must be invoked with a \csname. That is to say, I would like to determine if \ABC123 (aka \csname ABC123\endcsname) is defined or not.

\documentclass{article}

\begin{document}
\ifdefined\A \verb|\A| is defined as ``\A''\else \verb|\A| is undefined\fi

\def\A{I am defined}

\ifdefined\A \verb|\A| is defined as ``\A''\else \verb|\A| is undefined\fi

\expandafter\ifdefined\csname ABC123\endcsname \verb|\ABC123| is defined\else 
  ABC123 is undefined\fi.  
{\bfseries$\leftarrow$Here I was hoping to detect undefined}

\expandafter\def\csname ABC123\endcsname{abc123}

\expandafter\ifdefined\csname ABC123\endcsname \verb|\ABC123| is defined as
  ``\csname ABC123\endcsname''\else \verb|\ABC123| is undefined\fi

\end{document}

enter image description here

17

Use \ifcsname A\endcsname, which is exactly what you want.

With \expandafter\ifdefined\csname A\endcsname, in case \A is not defined, it will become equivalent to \relax. This doesn't happen with \ifcsname.

\documentclass{article}

\begin{document}
\ifdefined\A \verb|\A| is defined as ``\A''\else \verb|\A| is undefined\fi

\def\A{I am defined}

\ifdefined\A \verb|\A| is defined as ``\A''\else \verb|\A| is undefined\fi

\ifcsname ABC123\endcsname \verb|\ABC123| is defined\else
  ABC123 is undefined\fi.
{\bfseries$\leftarrow$Here I was hoping to detect undefined}

\expandafter\def\csname ABC123\endcsname{abc123}

\ifcsname ABC123\endcsname \verb|\ABC123| is defined as
  ``\csname ABC123\endcsname''\else \verb|\ABC123| is undefined\fi

\end{document}

enter image description here

| improve this answer | |
  • 2
    Thank you for both the answer and the bonus tidbit concerning \relax. – Steven B. Segletes Mar 6 '15 at 0:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.