Increment Counter in Section Title

counterssection-titles

I wonder why I can not call \stepcounter within a section title.

For example, this code works fine:

\documentclass{article}
\newcounter{mycounter}
\begin{document}
\section{Title \themycounter}
\stepcounter{mycounter}
\end{document}

But this code encounter attached error:

\documentclass{article}
\newcounter{mycounter}
\begin{document}
\section{Title \themycounter \stepcounter{mycounter}}
\end{document}

Error:

The control sequence marked <to be read again> should
not appear between \csname and \endcsname.

d:/D-Repos/tmp/counter.tex:7: Missing \endcsname inserted.
<to be read again> 
                   \MessageBreak 
l.7 ...itle \themycounter \stepcounter{mycounter}}

Best Answer

You should either run \stepcounter{mycounter} before \section or -- if it occurs in the argument of \section -- "protect" the \stepcounter directive via a \protect directive. (@DavidCarlisle has already mentioned the second alternative in a comment.)

Addendum (see also David Carlisle's comment below): If your document contains a \tableofcontents directive, you should not use the second method, as otherwise the numbering will be messed up.

enter image description here

\documentclass{article}
\newcounter{mycounter}
\renewcommand\themycounter{\Alph{mycounter}}

\begin{document}
\stepcounter{mycounter}\section{Title \themycounter}

\section{\protect\stepcounter{mycounter}Title \themycounter}
\end{document}
Related Question