This question already has an answer here:

I know I can create a new command with an optional parameter with

\newcommand{\mycommand}[2][Hello]{\textbf{#1} #2}

I would like to have the command such that there is an optional parameter which takes the value of the non optional if not specified. Something like this

\newcommand{\mycommand}[2][#2]{\textbf{#1} #2}

Any ideas?

marked as duplicate by Ryan Reich, Xavier, Stefan Kottwitz May 9 '13 at 6:44

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


LaTeX kernel solution

\def\@mycommand[#1]#2{\textbf{#1} #2}

See this answer for a description of \@dblarg.

xparse solution

\NewDocumentCommand{\mycommand}{o m}
 {\textbf{\IfValueTF{#1}{#1}{#2}} #2}

\IfValueTF{#1}{A}{B} looks whether the optional argument was specified; if it was, it delivers A, otherwise B. In the previous definition, A is #1 and B is #2 as you wished.

The xparse solution is more robust.


Using a very elementary approach, you can make the optional argument default to some macro that you can test against:

enter image description here

  \textbf{\ifx\@empty#1\relax#2\else#1\fi} #2}
\mycommand{Second} \par

In the above example, the optional argument to \mycommand is set to \@empty by default (if it's not specified). Using \ifx\@empty#1\relax, you can test whether the default argument is supplied (and therefore, #1 is actually missing). Then, print #2, otherwise, print #1.

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