2

I defined a new command,

\newcommand{\Test}[1][p]{\ensuremath{n_{\mathrm{dof}}^{\mathrm{Q#1}} }}

with one optional argument, which is either 1 or 0. If I call \Test without the parameter, I get the desired output, that is the correct subscript Qp. However, calling \Test{2} gives the subscript Qp either and the argument 2 is located elsewhere. My intuition is to retrieve Q2 in case of calling \Test{2}. I can add a picture if necessary but I hope it is clear what I refer to.

Is there something I do not encounter correctly?

campa
  • 31,130
Simon
  • 281

1 Answers1

5

You have misunderstood the syntax of optional parameters: they are delimited by square brackets. When you write1)

\newcommand{\Test}[1][p]{n_{\mathrm{dof}}^{\mathrm{Q#1}}}

then \Test scans whether a square bracket follows, or not. Your macro should be used either as \Test (and then you'll get Qp as superscript), or as \Test[2].

\documentclass{article}
\newcommand{\Test}[1][p]{n_{\mathrm{dof}}^{\mathrm{Q#1}}}
\begin{document}
$\Test$, $\Test{2}$, $\Test[2]$
\end{document}

enter image description here


1) I wouldn't use \ensuremath unless my life depended on it; and even in that case I would ponder whether my life is precious enough...

campa
  • 31,130
  • nice answer (+1), but you suggest to use instead of \mathrm that your lije be saved ;-) – Zarko Aug 19 '21 at 11:56
  • Thank you (+1)! Regarding your footnote, would you share your knowledge why \ensuremath is not a good choice? :-) – Simon Aug 19 '21 at 12:42
  • @Simon Some years ago I had a situation where \ensuremath was wreaking havoc in such a sneaky way that it took me hours to work out. Admittedly, I was an absolute TeX novice and didn't know how to debug properly. Anyway, I learnt to separate math from text and not to rely on laziness. Have a look at https://tex.stackexchange.com/q/34830/82917 for some discussion. – campa Aug 19 '21 at 12:48