68

Possible Duplicate:
Different command definitions with and without optional argument

I would like to define a macro which takes an optional argument, and behaves in different ways depending on if the optional argument is given or not. As a very simple example, I would like to define a new macro

\newcommand{\example}[0][]{macro definition}

which outputs

optional argument was omitted

if the optional argument was omitted, and

optional argument was given

if the optional argument was given. How can I achieve this?

1 Answers1

100
\documentclass[parskip]{scrartcl}
\usepackage[margin=15mm]{geometry}
\usepackage{xifthen}

\newcommand{\test}[1][]{%
\ifthenelse{\equal{#1}{}}{omitted}{given}%
}

\begin{document}

The optional argument was \test[].

The optional argument was \test[shubidu].

\end{document}

Which results in

enter image description here

Tom Bombadil
  • 40,123
  • 58
    Slightly better: \ifthenelse{\isempty{#1}} (the \isempty test is provided by xifthen. – egreg Jun 05 '12 at 11:11
  • 7
    Oh, I didn't know it existed. You live and learn! – Tom Bombadil Jun 05 '12 at 11:14
  • 1
    Also, it seems \ifx can be used: \newcommand{\test}[1][]{ \def\tst{#1} \ifx\tst\empty \typeout{optional argument was omitted} \else \typeout{optional argument was given: '#1'} \fi } – sdaau Jun 03 '15 at 17:03
  • @TomBombadil Is there a way to make \test accept its argumets with {} rather than with []? – yohbs Oct 27 '15 at 12:45
  • 6
    @yohbs: Yes, but then it would not be an optional argument anymore: \newcommand{\test}[1]{\ifthenelse{\isempty{#1}{}}{omitted}{given}} – Tom Bombadil Oct 27 '15 at 12:49
  • @TomBombadil why does it stop working as an optional argument if you want to use {}? It is just because the {} works as a grouping here, and not as the "parenthesis" for a command or something? Essentially: with the code you wrote above, why does it fail to work as expected when I write \test{testarg}? – Marses Jul 14 '20 at 16:13
  • Additionally, when I make the argument non-optional, why does \test[testarg] not work as expected (it seems not actually pass any argument). – Marses Jul 16 '20 at 11:43
  • 1
    I am trying to define a command as such: \newcommand{\gesetze}[2]{http://www.gesetze-im-internet.de/#1/\ifthenelse{\equal{#2}{}}{}{__#2.html}}

    The idea is that, if an optional second argument is given, it appends __#2.html to the url, and if not, it ends after #1/. However, this gives an error.

    – Marie. P. Aug 01 '20 at 22:24