[Tex/LaTex] Error with \newcommand and \section

errorsmacrossectioning

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).

Best Answer

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

enter image description here

\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} 
Related Question