The general idea behind creating "optional arguments" is to first define an intermediate command that scans ahead to detect what characters are coming up next in the token stream and then inserts the relevant macros to process the argument(s) coming up as appropriate. This can be quite tedious (although not difficult) using generic TeX programming. LaTeX's \@ifnextchar
is quite useful for such things.
The best answer for your question is to use the new xparse
package. It is part of the LaTeX3 programming suite and contains extensive features for defining commands with quite arbitrary optional arguments.
In your example you have a \sec
macro that either takes one or two braced arguments. This would be implemented using xparse
with the following:
\documentclass{article}
\usepackage{xparse}
\begin{document}
\DeclareDocumentCommand\sec{ m g }{%
{#1%
\IfNoValueF {#2} { and #2}%
}%
}
(\sec{Hello})
(\sec{Hello}{Hi})
\end{document}
The argument { m g }
defines the arguments of \sec
; m
means "mandatory argument" and g
is "optional braced argument". \IfNoValue(T)(F)
can then be used to check whether the second argument was indeed present or not. See the documentation for the other types of optional arguments that are allowed.