4

I have defined a conditional using the ifthen package as:

\newcommand{\Switch}[1] { \ifthenelse{\equal{#1}{1}}{Test1}{Test2} }

Running this command works without problem. However, if I try to place it within a Figure Caption, it produces an error (i.e., \Switch{1} and \caption{Example text} work fine, but \caption{\Switch{1}} does not).

Is this expected behavior? How do I work around it to produce a conditional caption?

3 Answers 3

6

The \ifthenelse command appears to be fragile? \caption{\protect\Switch{1}} works.

3

As a modern alternative, you can use the commands from the etoolbox package:

\newcommand*{\Switch}[1]{\ifnumequal{#1}{1}{Test1}{Test2}}

Or the xparse package:

\ExplSyntaxOn
\NewDocumentCommand \Switch { m } {
  \int_compare:nNnTF { #1 } = { \c_one } {
    Test1
  } {
    Test2
  }
}
\ExplSyntaxOff
1
  • 2
    You don't like \int_compare:nTF { #1=1 }? No need for using the constant here (in fact, we shouldn't be promoting their use much, really). Commented Jan 3, 2011 at 16:31
0

The other solutions work, just adding this one for completeness. It also has the advantage of not needing \protect.

Declare your command as robust with:

\DeclareRobustCommand{\Switch}[1] { \ifthenelse{\equal{#1}{1}}{Test1}{Test2} }

You can now use \caption{\Switch{1}} just fine.

See this question for details about the difference between \newcommand and \DeclareRobustCommand.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .