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.