# Dynamically generated label

I would like to generate a label using a command that uses conditions:

\newcommand{\paperPrefix}[1][]{\ifthenelse{\equal{#1}{}}{\ifthenelse{\equal{\activePaper}{}}{}{\activePaper\_}}{#1\_}}


Basically it should return #1_ if called with the optional parameter, \activePaper_ if the macro activePaper is define (\def\activePaper{...}) and nothing ('') otherwise.

However when I use it:

\label{\paperPrefix[MyPrefix]{}image}


Instead of defining a label in the form

\label{MyPrefix_image}


It complains that:

! Missing \endcsname inserted.<to be read again>\let ...eco]{}}{{1}{1}{Introduction}{chapter.1}{}}


So I was wondering, how to solve this.

• The argument of \label must be expandable. LaTeX macros with optional arguments are not expandable, \ifthenelse is not expandable. Also \_ is problematic. Therefore the interface has to be changed. For example, a macro performs the unexpandable stuff and defines a simple macro, which can be used later in \label. – Heiko Oberdiek May 20 '16 at 16:57

Apart from the fact that \ifthenelse does not work by expansion

\label{\paperPrefix[MyPrefix]{}image}


only has one argument (in [] ) so the {} before image is untouched and would form part of the label.

I think you want

\newcommand{\paperPrefix}[1]{\ifx\activePaper\defaultPaper\else#1_\fi}


together with

\newcommand\defaultPaper{}%or anything really
\newcommand\activePaper{}%same as above


then \paperPrefix{mypaper} (with {} not []) will expand to nothing by default or to mypaper_ if \activepaper has been redefined.
