[Tex/LaTex] Optional arguments in \def

macrosoptional argumentssymbols

I want to re-define the \sqrt command (as detailed in Nice-looking p-th roots), and so far I have the following:

\documentclass{article}

\usepackage{fouriernc} % use the New Century Schoolbook font
\usepackage{amsmath}

\let\oldsqrt\sqrt
\def\sqrt[#1]{\oldsqrt[\leftroot{-3}\uproot{3}#1]}

\begin{document}
This $\sqrt[p]{a}$ looks better than $\oldsqrt[p]{a}$,
since the $p$ does not intersect the root symbol.
\end{document}

However, when I try writing \sqrt{a}, I get an error. How can I make the #1 argument optional, so that if it is not passed in, it leaves that area above the root symbol blank (as it would in the default \sqrt command)?

(This is a follow-up to the comments on David's and Harish's answers to above-mentioned question.)

Best Answer

If you want commands with at most one optional argument, LaTeX's built in \newcommand and \renewcommand are an easy way to define them. The syntax is

\(re)newcommand⟨\name⟩[⟨number of arguments⟩][⟨default value for the first argument⟩]{⟨code⟩]

If you specify the second optional argument, then the first argument to \name will be optional. So in your case one can simply use

\renewcommand\sqrt[1][]{\oldsqrt[\leftroot{-3}\uproot{3}#1]}

Note that (as in your question), we do not need to specify the second argument, because \oldsqrt will look for it anyway, so that this definition is functionally equivalent to

\renewcommand\sqrt[2][]{\oldsqrt[\leftroot{-3}\uproot{3}#1]{#2}}

If you need several optional arguments or an argument other than the first one should be optional, you can either chain \@ifnextchars (as in Yiannis' answer), or use xparse (as in Peter's answer).

Related Question