# newcommand with two arguments, one optional

I'm struggling with a command that doesn't do what I expect. This is my code

\newcommand{\expectation}[2][]{\mathrm{E}_{#1}\left[#2\right]}

\begin{document}
I get $\expectation{A}{B}$, but I expect $\mathrm{E}_{A}\left[B\right]$\\
Optional arguments, I get $\expectation{B}$, and I expect $\mathrm{E}\left[B\right]$
\end{document}


and this is the output


(Even worse: I'm sure everything worked as intended yesterday. Today it doesn't anymore)

Edit: turns out this was due to a fixed bug in Texstudio. Optional arguments have to be called with brackets

• Invoke it as \expectation[A]{B} with square, not curly brackets around the A. It is an optional argument. Curly braces are for mandatory arguments. Aug 11 '15 at 19:17
• Also it might be an idea to use \ifblank from etoolbox to test if the _{#1} is even needed. Aug 11 '15 at 19:25
• Thanks, now I understand. My editor (TeXstudio) suggests to use curly brackets for both arguments Aug 11 '15 at 19:32
• As it turns out, this is a known bug. Will be fixed in the next release Aug 11 '15 at 19:38
• You also might not want to have the left right construction as it easily becomes too excessive. Aug 11 '15 at 22:25

I would use the xparse package as it keeps the default behaviors for an optional argument very manageable.

\documentclass[10pt]{article}

\usepackage{xparse}

%\ExplSyntaxOn
\DeclareDocumentCommand{\expectation}{ O{} m }{%
$\mathrm{E}_{#1}\left[#2\right]$%
}
%\ExplSyntaxOff

% choose a different way of producing subscripts if you need ExplSyntax

\begin{document}
I get \expectation[A]{B}, but I expect $\mathrm{E}_{A}\left[B\right]$\\
Optional arguments, I get \expectation{B}, and I expect $\mathrm{E}\left[B\right]$
\end{document}