Optional argument for newcommand

argumentsmacrosmath-modeoptional arguments

Suppose we define the following macros:

\newcommand*{\G}[1][G]{\mathbb #1}
\newcommand*{\Cop}[1][]{\Delta_{#1}}

For the first one, if we use $\G$ it produces in the pdf what $\mathbb{G}$ does and if we use $\G[H]$, then in this case it produces what $\mathbb{H}$ does. Now, if we use $\Cop[\G]$ then it produces $\Delta_{\mathbb{G}}$ as expected. But the problem is, whenever we use $\Cop[\G[H]]$ to produce the result of $\Delta_{mathbb{H}}$ there is the following error:

Argument of \\G has an extra }

What is actually wrong in there?

Best Answer

Optional arguments aren't quite the same as mandatory ones. They start with a [, and they are delimited by the next ] (that's important). When you do

\Cop[\G[H]]
%   1  2 34

\Cop is processed first, and its optional argument starts with the first [ (1), and is delimited by the next ] (3), so its argument is what's between [ (1) and ] (3), that is, \G[H. Replacing \Cop by its definition with the argument:

\Delta_{\G[H}]

and you can see where it goes wrong.

To solve it, either "hide" the inner argument in braces:

\Cop[{\G[H]}]

or use ltcmd to define the commands:

\NewDocumentCommand \Cop { O{G} } {\mathbb{#1}}
\NewDocumentCommand \G { O{} } {\Delta_{#1}}

(ltcmd has an extra layer of parsing which ensures that [ and ] are balanced within optional arguments).

Related Question