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
    Note that [0] here would create a command with no arguments at all: you need [1][] to have one optional argument.
    – Joseph Wright
    Jun 5, 2012 at 11:06

1 Answer 1




The optional argument was \test[].

The optional argument was \test[shubidu].


Which results in

enter image description here

  • 58
    Slightly better: \ifthenelse{\isempty{#1}} (the \isempty test is provided by xifthen.
    – egreg
    Jun 5, 2012 at 11:11
  • 7
    Oh, I didn't know it existed. You live and learn! Jun 5, 2012 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 3, 2015 at 17:03
  • 6
    @yohbs: Yes, but then it would not be an optional argument anymore: \newcommand{\test}[1]{\ifthenelse{\isempty{#1}{}}{omitted}{given}} Oct 27, 2015 at 12:49
  • 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 1, 2020 at 22:24

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