Error with \newcommand and \section

I'm trying to typeset an article. In the preamble, I defined these two things:

\newcommand{\leftexp}[2]{{\vphantom{#2}}^{#1}{#2}}

\newcommand{\hr}{\leftexp{*}{\mathbb{R}}}


However, when I try to use $\hr$ in a section, as in:

\section{Constructing $\hr$}


I get an error:

Incomplete \iffalse; all text was ignored after line 1.


Any idea what could be causing this? Everything works just fine if I don't have the $\hr$ in the section (e.g. It typesets just fine if I have \section{Constructing $\mathbb{R}$}, say).

-
Since the argument of \section "moves", protecting it seems to solve your problem: \newcommand{\hr}{\protect\leftexp{*}{\mathbb{R}}}, or just using \protect\hr in your sectional header. –  Werner Feb 1 '12 at 23:19

It'll be a fragile command, and \section is a moving argument, so use \protect or declare it with \DeclareRobustCommand

\documentclass{article}

\usepackage{amsmath,amssymb}

\newcommand{\leftexp}[2]{{\vphantom{#2}}^{#1}{#2}}

\newcommand{\hr}{\leftexp{*}{\mathbb{R}}}

\DeclareRobustCommand{\leftexpB}[2]{{\vphantom{#2}}^{#1}{#2}}
\DeclareRobustCommand{\hrB}{\leftexpB{*}{\mathbb{R}}}

\begin{document}

\tableofcontents

\section{Constructing $\protect\hr$}

aa

\section{Constructing $\hrB$}

aa

\end{document}

-
Thanks a lot. I'm just learning these things, so may I ask what exactly is a "moving argument" and a "fragile command"? Alternatively, what does \protect do? –  FPP Feb 1 '12 at 23:22
Ah, the honest answer is a "moving argument" is any argument in which things go wrong sometimes. A fragile command is a command that goes wrong in a moving argument, and \protect normally does nothing but in each such command it is locally defined to do whatever necessary to fix the problem. This case is typical, the heading is typeset as the section head, but also perhaps written to the toc file and/or used at a different font size in a page head. \protect holds the command unexpanded so it is written to the toc file unexpanded and only expanded when the toc is read back in. –  David Carlisle Feb 1 '12 at 23:26
–  Joseph Wright Feb 2 '12 at 17:21

You got the (in)famous "fragile command in moving argument" problem. The stuff in \section is written into table of contents, which breaks things.

The following works:

\newcommand{\leftexp}[2]{{\protect\vphantom{#2}}^{#1}{#2}}
\newcommand{\hr}{\leftexp{*}{\mathbb{R}}}

-