# Protect fragile variable in file path. Case of \ifthenelse in \includegraphics{}

In this script:

\documentclass{article}
\usepackage{ifthen}
\usepackage{graphicx}
\newcommand{\myfigure}[1]{%
\def\mydirectory{\ifthenelse{\equal{#1}{first}}{dir1}{dir2}}

my directory is \mydirectory

\begin{figure}
%    \includegraphics[width=0.45\textwidth]{\protect\mydirectory/mypic.pdf}%
\includegraphics[width=0.45\textwidth]{example-image-a}%
\caption{picture in \protect\mydirectory}
\end{figure}

}

\begin{document}
\myfigure{first}
\end{document}


I \protect the fragile variable \mydirectory in \caption - see comments to How to protect a fragile command in a moving argument? The case of macro containing \ifthenelse in \caption.

However, when I provide:

\includegraphics[width=0.45\textwidth]{\mydirectory/mypic.pdf}


the classical symptoms of a fragile \ifthenelse appear:

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


that are not cured even by \protect:

\includegraphics[width=0.45\textwidth]{\protect\mydirectory/mypic.pdf}

How to protect a fragile variable in a file path?

• Ifthenelse is not expandable. You can't use it in this place. – Ulrike Fischer Oct 15 '18 at 11:29
• I think it should by now be clear to you that \ifthenelse doesn't work by pure expansion. A method with \ifstreq similar to one I suggested for another case will work flawlessly. – egreg Oct 15 '18 at 11:41
• This can not work. – David Carlisle Oct 15 '18 at 12:28

I would not use ifthenelse but if you use it (or any other test mechanism) you want \mydirectory to expand to the directory name, not to a complicated sequence of assignments and tests that may eventually typeset a directory name.

so

\newcommand{\myfigure}[1]{%
\def\mydirectory{\ifthenelse{\equal{#1}{first}}{dir1}{dir2}}


can not possibly work, you would need

\newcommand{\myfigure}[1]{%
\ifthenelse{\equal{#1}{first}}%
{\def\mydirectory{dir1}}%
{\def\mydirectory{dir2}}%
}


so that the definition of \mydirectory is either dir1 or dir2.

• As you define \mydirectory in {\def\mydirectory{dir1}} will not \mydirectory live only inside the scope {}? – Viesturs Oct 15 '18 at 12:36
• @Viesturs no: {}: that delimit macro arguments do not form a group. – David Carlisle Oct 15 '18 at 12:37
• Is it advisable to use \newcommand in place of \def? – Viesturs Oct 15 '18 at 14:25