Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question

marked as duplicate by Loop Space, David Carlisle, egreg, lockstep, tohecz Jun 5 '12 at 11:11

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.

    
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 '12 at 11:06

1 Answer 1

up vote 7 down vote accepted
\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

share|improve this answer
4  
Slightly better: \ifthenelse{\isempty{#1}} (the \isempty test is provided by xifthen. –  egreg Jun 5 '12 at 11:11
    
Oh, I didn't know it existed. You live and learn! –  Tom Bombadil Jun 5 '12 at 11:14

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