# How to put a conditional construct in \edef

\ifthenelse works fine normally, but when used in \edef:

\documentclass{article}
\usepackage{ifthen}
\newcommand\testing[1][]{%
\edef\tmp{\ifthenelse{\equal{#1}{}}{Blank}{#1}}%
}
\begin{document}
\testing
\end{document}


I get:

! Undefined control sequence.
<argument> \equal
{}{}
l.10


I also get this error when I use \ifthenelse in a \putbib command (from the bibunits package).

Is there a way around that?

-

Put \noexpand in front of the inner macros which should not be expanded:

\documentclass{article}
\usepackage{ifthen}
\newcommand\testing[1][]{%
\edef\tmp{\noexpand\ifthenelse{\noexpand\equal{#1}{}}{Blank}{#1}}%
}
\begin{document}
\testing
\end{document}


If you actually want the full expression be expanded, then you can only use code which is fully expandable and do not use temporary assignments etc. You could also move the \edef into the true an false clauses instead.

-

It's not possible to use \ifthenelse in an \edef; Martin's approach will only defer the evaluation and so the \edef does only expansion of #1 (which might be what you want).

In order to test if an argument is empty, the safer test is

\if\relax\detokenize{#1}\relax
<empty>
\else
<not empty>
\fi


One can also define a "TF" variant:

\makeatletter
\newcommand{\ifEmptyTF}[1]{%
\if\relax\detokenize{#1}\relax
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi}
\makeatother


and then your code can become

\newcommand{\testing}[1][]{\ifEmptyTF{#1}{Blank}{#1}}


An "expanded" version can be obtained with the help of \pdfstrcmp (called \strcmp in XeTeX):

\usepackage{pdftexcmds}
\makeatletter
\newcommand{\ifExpandedEmptyTF}[1]{%
\ifnum\pdf@strcmp{#1}{}=\z@
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi}
\makeatother


(pdftexcmds defines \pdf@strcmp to do the right thing independent of the typesetting engine used).

For example \ifEmpty{\empty} will evaluate to false, while \ifExpandedEmptyTF{\empty} will evaluate to true, given that \empty is defined by

\def\empty{}

-