Special behavior if optional argument is not passed
\makeatletter
\newcommand{\mycommand}[1][\@nil]{%
\def\tmp{#1}%
\ifx\tmp\@nnil
no argument
\else
argument #1
\fi}
\makeatother
\mycommand zzzz \mycommand[hello] zzz
You can do it easily with xparse
:
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\mycommand}{o}{%
% <code>
\IfNoValueTF{#1}
{code when no optional argument is passed}
{code when the optional argument #1 is present}%
% <code>
}
\begin{document}
\mycommand
\mycommand[HERE]
\end{document}
This will print
code when no optional argument is passed
code when the optional argument HERE is present
For an environment it's similar
\NewDocumentEnvironment{myenv}{o}
{\IfNoValueTF{#1}{start code no opt arg}{start code with #1}}
{\IfNoValueTF{#1}{end code no opt arg}{end code with #1}}
Other code common to the two cases can be added at will. As you see, xparse
also allows (but it's not mandatory) to use the argument specifiers also in the end part.