# 2014-08-08 A problem with a command with an optional star

TL;DR: I wanted to be smart, and it backfired.

I’m currently writing a (longish) document on mathematics. Among other things, I write about the Hausdorff metric, which I denote by `d_H`. Since this notation appears quite often, I decided to write a command for it:

```\newcommand{\dH}{{d_H}}
```

Now what are the extra braces for? Sometimes I want to talk about a ball with respect to the Hausdorff metric, denoted by `B_{d_H} `– for that, I wanted to write `B_\dH`. Without the extra braces this won’t work (for obvious reasons).

So far, so good. But there’s another catch: I want a similar notion to the Hausdorff metric, which I denote `d_H^*`. With my definition, `\dH^*` won’t work (can you see why?). So I wanted to be clever, and use an optional star; this way, I could write `\dH` or `\dH*`. I did this:

```\newcommand{\dH}{\@ifstar{d_H^*}{d_H}}
```

(The `\@ifstar{whatever}{something else} `macro (which must come as the last thing in your defined command!!!) “peeks ahead”, and if it sees a star (possibly after some spaces), it executes `whatever`, and `something else` otherwise.) But my ability to write `B_\dH` is lost now! And of course, adding braces around `\@ifstar` won’t help: it will then never “see” the star.

(Please note that if you want to define commands accepting optional stars and/or optional parameters, the `xparse` package is a better way to go – the `\@ifstar` macro is a low-level, LaTeX2e concept.)

It seems that there’s no way out of this dilemma. It’s not a big deal, I can write `B_{\dH} `(which is cleaner LaTeX syntax anyway), but I’m curious whether there’s any way to eat this cake and have it, too.

Edit: yes, there is a way, as this übercool answer from Enrico Gregorio shows. As pointed out in the comments, it’s better to stick to `B_{\dH} `syntax, though.