The three objects behind every number
A LaTeX counter is not a macro. \newcounter{foo} creates an integer register named \c@foo (so \value{foo}, which is literally \csname c@foo\endcsname, is a TeX \count), and it creates four companion macros that answer different questions. \thefoo is the printed representation, the one a heading or an environment shows. \p@foo is a reference prefix that is glued in front of \thefoo only when \label writes a value into the .aux. \theHfoo is the destination representation hyperref uses to name the PDF anchor. And \cl@foo is the reset list: the counters that go back to zero whenever foo is stepped.
Confusing the first two is the source of most "my numbering is wrong but I cannot see why" reports. Redefining \thefoo changes the page and the reference; redefining \p@foo changes only what \ref says; redefining \theHfoo changes nothing the reader sees and everything a PDF viewer does.
The representations are themselves macros you can redefine: \arabic, \roman, \Roman, \alph, \Asbuk and \asbuk (the last two for Cyrillic, provided by babel) are the standard ones, plus \fnsymbol for the symbol sequence. Any of them can be combined with literal text, so \renewcommand{\theexercise}{(\alph{exercise})} is legal, and \thepage, \thechapter, \thesection are ordinary counters like any other.
One constraint is worth memorising because it silently breaks documents: the kernel notes that \thefoo and \p@foo must be defined so that \edef\bar{\thefoo} captures the value at that moment. That is what \arabic{} and friends guarantee, and what a definition built out of macros that expand late does not — which is why a \thefoo built on top of a package that redefines counters can print the last value in the document rather than the current one.
n_{\text{print}} = (n_{\text{parent}},\ n_{\text{raw}}) \qquad (2,4) \mapsto 2.4
The three-line contract: newcounter, setcounter, usecounter
Line one — \newcounter{foo}[parent]. It declares the register and, if you give the optional argument, adds foo to the parent's reset list via the internal \@addtoreset. That is all the optional argument does. It does not change \thefoo: after \newcounter{exercise}[section] the number still prints as 4, not 2.4. The reason the optional argument has this reputation is that the standard classes do the printing part by hand — article.cls contains \newcounter{subsection}[section] followed by \renewcommand\thesubsection{\thesection.\arabic{subsection}} — and two lines read as one.
Line two — \setcounter{foo}{<value>}. Set and its sibling \addtocounter are global (the kernel wraps them in \global), so a counter changed inside a group keeps the new value afterwards, unlike an ordinary macro. The second argument is a ⟨integer expression⟩, which is why \setcounter{chapter}{\value{chapter}+1} and \addtocounter{page}{-2} are both legal, and why you must not write \stepcounter where an expression is expected, or a stray space inside the braces: the argument is read as a number and any token it cannot parse ends the expression silently.
Line three — \usecounter{foo}. This is the counter interface of the list environment, and it is what enumerate is built from. Written in the setup argument, \begin{list}{\label}{\usecounter{enumi}}, it declares that \item should step foo and that \label inside the list refers to that counter. The single line of kernel source behind it is \def\usecounter#1{\@nmbrlisttrue\def\@listctr{#1}\setcounter{#1}\z@} — and note the last part: \usecounter zeroes the counter. So \setcounter{exercise}{6} before a list is forgotten; the correct way to start a list at seven is to write the \setcounter after \usecounter inside the same setup argument.
v = 4 \;\Longrightarrow\; \mathrm{iv},\ \mathrm{d},\ \mathrm{IV},\ 4
\documentclass[11pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage[a4paper,margin=2.5cm]{geometry}
% ---- 1. the counter exists, and it resets with its parent.
% Note: this is ONLY the reset. \newcounter does not touch the printed form.
\newcounter{exercise}[section]
% ---- 2. how the number is printed on the page.
\renewcommand{\theexercise}{\thesection.\arabic{exercise}}
% ---- 3. a solution counter whose heading is short but whose \ref is full:
% \p@<counter> is prefixed to \the<counter> only when \label is written.
\newcounter{solution}
\renewcommand{\thesolution}{\arabic{solution}}
\makeatletter
\renewcommand{\p@solution}{Solution \thesection.} % \ref -> "Solution 1.3"
\makeatother
\newenvironment{solution}
{\par\smallskip\noindent\refstepcounter{solution}%
\textbf{Solution \thesolution.}\ }
{\par\medskip}
% ---- a hand-built numbered environment: three lines of machinery
\newenvironment{exercise}
{\par\medskip\noindent
\refstepcounter{exercise}% <- makes \label work
\textbf{Exercise \theexercise.}\itshape\space}
{\par\medskip}
\begin{document}
\section{First-order equations}\label{sec:one}
\begin{exercise}
Solve $x^{2} + 2bx + c = 0$ and verify the roots. \label{ex:quad}
\end{exercise}
Reference to \textbf{\ref{ex:quad}} works only because the environment called
\verb|\refstepcounter|, not \verb|\stepcounter|.
\begin{solution}
Complete the square: $(x+b)^{2} = b^{2} - c$. \label{sol:quad}
\end{solution}
The heading reads \thesolution{} while \verb|\ref{sol:quad}| reads
\ref{sol:quad}, because \verb|\p@solution| adds the prefix that only the
reference sees.
\subsection{A list that reuses a counter}
A \texttt{list} environment counts with any counter you hand it, through
\verb|\usecounter| --- which \emph{resets that counter to zero} when the list
begins, so a preceding \verb|\setcounter| has to be repeated inside the setup:
\begin{list}{\textbf{\theexercise.}}{\usecounter{exercise}\setcounter{exercise}{6}%
\setlength{\leftmargin}{3.2em}\setlength{\labelwidth}{2.6em}}
\item continues from 7, because \verb|\item| steps the list counter.
\item and 8 here.
\end{list}
\section{Second section}
\begin{exercise}
The counter restarted: this is \ref{ex:quad} again? No ---
this new exercise is \arabic{exercise} in section \thesection.
\end{exercise}
\subsection*{Skipping and setting}
\setcounter{exercise}{10}
Now manually at \theexercise.
\addtocounter{exercise}{-3}
And after a negative step, \theexercise.
\end{document}
stepcounter versus refstepcounter
\stepcounter{foo} does two things: it increments the register and it resets every counter on foo's reset list. \refstepcounter{foo} does those two plus one, and the extra one is the difference between a working environment and a decorative one. It stores \@currentlabel — the string \p@foo\thefoo, expanded at that instant — and it also records \@currentHref and \@currentcounter, the destination name and the identity of the counter.
Because \label{name} writes \@currentlabel into the .aux, a counter moved with plain \stepcounter cannot be referenced: \label after it records whatever the previous \refstepcounter left behind, so \ref{ex:one} prints the section number, or the previous exercise, or ??. This is the exact reason the standard theorem-like environments use \refstepcounter and the reason the "label after the counter" rule from the cross-referencing lesson has a mechanism behind it.
Use \stepcounter deliberately when you want a number to advance without becoming referenceable: a running tally used in a footer, a loop counter, or an unnumbered environment that shares a counter for spacing. The distinction also explains the behaviour of \item, which is where the list machinery calls \refstepcounter\@listctr — hence a \label inside enumerate picks up enumi, and a \label in a itemize picks up nothing at all, because itemize never sets \@nmbrlisttrue.
Reset hierarchies, and re-parenting a counter
Reset relationships live in lists named \cl@<parent>, and stepping a parent walks that list. The kernel arranges the familiar hierarchy — footnote? no: equation, figure, table and each sectional level reset with section, which resets with subsection's parent, and so on up to chapter in the book-family classes. You can add to a list with the internal \@addtoreset{child}{parent}, remove with \@removefromreset{child}{parent}, or use the user-level pair that has been part of the kernel since the 2018 release: \counterwithin{child}{parent} and \counterwithout{child}{parent}. On an older installation these come from the chngcntr package.
The two differ in more than name, and the difference is the one people trip over: \counterwithin does both halves of the job — it adds the reset and redefines \thechild to \theparent.arabic(child) — whereas \newcounter{child}[parent] does only the reset. So converting \newcounter{exercise}[chapter] into \newcounter{exercise} plus \counterwithin{exercise}{chapter} is not a cosmetic refactor: it is the version that also gives you the two-part number.
There is a third relationship, sharing rather than nesting: two environments counting in one series. amsthm expresses this with \newtheorem{lemma}[theorem]{Lemma}; with raw counters the equivalent is to point both at one register and print different words, which the kernel supports since the newest releases through counter aliases. Practically, either use a single counter and vary the heading macro, or accept that the two series run independently and say so in the text.
One last subtlety about resets: they happen when the parent is stepped, not when it is set. \setcounter{section}{3} does not reset the counters on cl@section, so a document that jumps sections by hand keeps stale equation numbers — one of the reasons a hand-written \setcounter{chapter}{...} in a multi-author book produces "Theorem 4.7" in chapter 5.
c_{\text{child}} \leftarrow 0 \quad \text{whenever} \quad c_{\text{parent}} \leftarrow c_{\text{parent}} + 1
Building a numbered environment yourself
A numbered environment is four lines, and once you have written it once the mystery of amsthm evaporates: \newenvironment{exercise}{\par\medskip\noindent\refstepcounter{exercise}\textbf{Exercise \theexercise.}\ }{\par\medskip}. The \refstepcounter is the reference machinery, \theexercise is the visible number, and the two \pars keep the environment from swallowing the surrounding paragraph. Add \addvspace{\medskipamount} instead of \medskip if you want consecutive exercises to share one gap rather than two.
Two refinements matter in real documents. To give an exercise an optional title, declare it with an argument — \newenvironment{exercise}[1]{...\textbf{Exercise \theexercise.\ifblank{#1}{}{ (#1)}}...}{...} (with etoolbox's \ifblank, or \ifstrempty from the kernel), and put the title into \@currentlabelname if you want \nameCref and the PDF bookmarks to carry it. To make the environment breakable or unbreakable, the tool is \needspace{3\baselineskip} or a minipage wrapper, not a counter change.
If you are writing this inside a class or package rather than a document, remember the @ letters are category-code-protected: wrap the definition in \makeatletter ... \makeatother, and if the environment needs to write internal state, prefer the hook interface the modern kernel offers (\AddToHook) to redefining \exercise by hand.
\documentclass[11pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage[a4paper,margin=2.5cm]{geometry}
% ---- 1. the counter exists, and it resets with its parent.
% Note: this is ONLY the reset. \newcounter does not touch the printed form.
\newcounter{exercise}[section]
% ---- 2. how the number is printed on the page.
\renewcommand{\theexercise}{\thesection.\arabic{exercise}}
% ---- 3. a solution counter whose heading is short but whose \ref is full:
% \p@<counter> is prefixed to \the<counter> only when \label is written.
\newcounter{solution}
\renewcommand{\thesolution}{\arabic{solution}}
\makeatletter
\renewcommand{\p@solution}{Solution \thesection.} % \ref -> "Solution 1.3"
\makeatother
\newenvironment{solution}
{\par\smallskip\noindent\refstepcounter{solution}%
\textbf{Solution \thesolution.}\ }
{\par\medskip}
% ---- a hand-built numbered environment: three lines of machinery
\newenvironment{exercise}
{\par\medskip\noindent
\refstepcounter{exercise}% <- makes \label work
\textbf{Exercise \theexercise.}\itshape\space}
{\par\medskip}
\begin{document}
\section{First-order equations}\label{sec:one}
\begin{exercise}
Solve $x^{2} + 2bx + c = 0$ and verify the roots. \label{ex:quad}
\end{exercise}
Reference to \textbf{\ref{ex:quad}} works only because the environment called
\verb|\refstepcounter|, not \verb|\stepcounter|.
\begin{solution}
Complete the square: $(x+b)^{2} = b^{2} - c$. \label{sol:quad}
\end{solution}
The heading reads \thesolution{} while \verb|\ref{sol:quad}| reads
\ref{sol:quad}, because \verb|\p@solution| adds the prefix that only the
reference sees.
\subsection{A list that reuses a counter}
A \texttt{list} environment counts with any counter you hand it, through
\verb|\usecounter| --- which \emph{resets that counter to zero} when the list
begins, so a preceding \verb|\setcounter| has to be repeated inside the setup:
\begin{list}{\textbf{\theexercise.}}{\usecounter{exercise}\setcounter{exercise}{6}%
\setlength{\leftmargin}{3.2em}\setlength{\labelwidth}{2.6em}}
\item continues from 7, because \verb|\item| steps the list counter.
\item and 8 here.
\end{list}
\section{Second section}
\begin{exercise}
The counter restarted: this is \ref{ex:quad} again? No ---
this new exercise is \arabic{exercise} in section \thesection.
\end{exercise}
\subsection*{Skipping and setting}
\setcounter{exercise}{10}
Now manually at \theexercise.
\addtocounter{exercise}{-3}
And after a negative step, \theexercise.
\end{document}
Telling hyperref and cleveref about a new counter
A new counter is invisible to the reference machinery until three further macros exist. hyperref's \autoref reads \<counter>autorefname, so you write \newcommand*{\exerciseautorefname}{Exercise} — without it \autoref{ex:one} prints the number with no noun. hyperref's destination name reads \theHexercise, which the kernel now pre-creates for every counter (since the 2024 release, \@definecounter defines \theH<name> as \number\value{<name>}); the bare integer is unique only within one parent, so in a report you should make it \thechapter.\arabic{exercise} or the log will fill with duplicate-destination warnings.
cleveref keeps its own two tables: \crefname{exercise}{exercise}{exercises} for the lower-case singular and plural, and \Crefname{exercise}{Exercise}{Exercises} for the capitalised pair. If a second environment should reuse the first one's vocabulary, \crefalias{subexercise}{exercise} says so without duplicating the strings. And if you want a format rather than a word — a bracketed number, a prefix inside math mode — \crefformat{exercise}{\textbf{#2#1#3}} gives you the three slots cleveref substitutes (opening, number, closing).
The \p@ prefix earns its place here. Because it is applied only when the reference string is built, you can let the heading print something short and \ref print something complete: \renewcommand{\thesolution}{\arabic{solution}} with \renewcommand{\p@solution}{\thesection.} gives a heading reading "Solution 3" and a cross-reference reading "Solution 2.3". The symmetric trick, putting the noun into \p@solution, makes \ref self-describing at the cost of printing the noun twice when you also use \autoref — so pick one layer to own the noun and stay there.
\underbrace{3}_{\text{printed by the heading}} \ne \underbrace{\text{Solution }2.3}_{\text{stored for the reference}}
\documentclass[12pt,a4paper]{report}
\usepackage[T1]{fontenc}
\usepackage{amsmath}
\usepackage[margin=2.5cm]{geometry}
\newcounter{exercise}[chapter]
\renewcommand{\theexercise}{\thechapter.\arabic{exercise}}
\newenvironment{exercise}
{\par\medskip\noindent
\refstepcounter{exercise}%
\textbf{Exercise \theexercise.}\ }
{\par\medskip}
% --- the machinery that has to be told about a new counter -------------
\makeatletter
% hyperref: \autoref builds its word from \<counter>autorefname
\newcommand*{\exerciseautorefname}{Exercise}
% hyperref: the destination name must be unique across the document
\renewcommand{\theHexercise}{\thechapter.\arabic{exercise}}
\makeatother
\usepackage{hyperref}
\hypersetup{colorlinks=true, linkcolor=blue}
\usepackage[capitalise]{cleveref}
% cleveref keeps its own tables: singular/plural, lower and upper case
\crefname{exercise}{exercise}{exercises}
\Crefname{exercise}{Exercise}{Exercises}
\begin{document}
\chapter{Linear algebra}
\section{Systems}\label{sec:sys}
\begin{exercise}\label{ex:one}
Solve $Ax = b$ for $A$ invertible.
\end{exercise}
\begin{exercise}\label{ex:two}
Solve the same system by row reduction.
\end{exercise}
All four reference styles at once: \ref{ex:one}, \theexercise,
\autoref{ex:two}, \cref{ex:one,ex:two}, \Cref{ex:two},
and \cpageref{ex:one}.
\subsection*{Re-parenting a counter}
\begin{verbatim}
\counterwithin{exercise}{section} % 2.3: reset with section, prefix included
\counterwithout{exercise}{section} % 7 : independent numbering again
\end{verbatim}
Both are kernel commands since the 2018 release; on an older installation the
package \texttt{chngcntr} provides them. \verb|\newcounter{exercise}[chapter]|
by contrast only ever does the reset half of that job.
\end{document}
Page numbers are counters too
\thepage is \arabic{page} in the default classes and nothing prevents you from treating it like any other counter — with one dangerous difference: page is stepped by the output routine, so \setcounter{page} is asynchronous. Setting it on page 7 does not renumber pages 1 to 6 retroactively, and setting it inside a box or a mark can land somewhere you did not intend.
The supported interface is \pagenumbering{<style>}, which does two jobs: it changes \thepage and it resets the counter to one. That is why \pagenumbering{arabic} at \mainmatter restarts the count, and why writing \setcounter{page}{1} instead of using \pagenumbering is a false economy: hyperref and every package that names page destinations keys off the numbering style, so a document with two pages numbered "1" in the same style produces duplicate destinations. Front matter in roman, body in arabic — \pagenumbering{roman}, then \clearpage, then \pagenumbering{arabic} — is the shape that keeps the two name spaces apart.
The remaining counters with special privileges are enumi through enumiv: the kernel supports four nested list levels and no more, each with a representation macro \theenumi..\theenumiv and a label macro \labelenumi..\labelenumiv. A fifth enumerate is an error, Too deeply nested, not a silent overflow. Redefining \labelenumii to \emph{(\theenumii)} changes the printed label, while \theenumii is what a \ref into that item produces — that pair, label versus reference value, is the \p@ story one level down.
Debugging a counter that misbehaves
Four questions answer almost every numbering complaint, and you can ask them of the log rather than of the source. What is the raw value? \typeout{COUNT = \number\value{exercise}} prints the integer itself, bypassing \the entirely. What is the printed form? \typeout{\meaning\theexercise} shows you the definition, which is where a missing parent prefix becomes obvious. What is on the reset list? \typeout{\meaning\cl@chapter} lists the children as \@elt {equation}\@elt {figure}.... What went into the aux file? Open .aux and read the \newlabel line.
Three failures and their signatures. A reference that prints the wrong object type means the label stands where no \refstepcounter had just run — move it after the command that steps your counter. A number that is right on the page and wrong in a \ref means \thefoo and \p@foo disagree; check whether a package or an old template redefined one of them. A numbering that will not reset means the parent relationship was expressed with \newcounter{foo}[parent] in a document where the parent is stepped by \setcounter rather than \stepcounter — a hand-set chapter resets nothing.
And when you are writing a class: prefer to declare a counter once, near the top, with its reset parent and its representation, and to leave the \p@ and \theH macros alone unless you need them. The counter system is one of the few places in LaTeX where the boring solution is also the correct one.
Lesson cheat sheet
One key line of code from each section — jump to it or copy it straight from here.
n_{\text{print}} = (n_{\text{parent}},\ n_{\text{raw}}) \qquad (2,4) \mapsto 2.4
\documentclass[11pt,a4paper]{article}
c_{\text{child}} \leftarrow 0 \quad \text{whenever} \quad c_{\text{parent}} \leftarrow c_{\text{parent}} + 1
\documentclass[12pt,a4paper]{report}
Common mistakes
- Assuming
\newcounter{foo}[section]makes the number print as2.1. The optional argument only registers the reset; you still need\renewcommand{\thefoo}{\thesection.\arabic{foo}}— or\counterwithin{foo}{section}, which does both. - Building a numbered environment with
\stepcounter. The number looks right but\label/\refcapture the previous counter; environments that are meant to be referenced must call\refstepcounter. - Writing
\setcounter{enumi}{4}before a list that uses\usecounter{enumi}.\usecounterzeroes the counter itself, so put the\setcounterafter it, inside the list setup argument. - Redefining
\thepageby hand instead of using\pagenumbering{...}.\pagenumberingalso resets to 1 and, more importantly, tells hyperref which name space the page destinations live in. - Expecting
\autorefor\crefto know a counter you invented: define\exerciseautorefnamefor hyperref and both\crefnameand\Crefnamefor cleveref, or you get a bare number or a??. - Resetting parents with
\setcounterand wondering why children keep counting: resets fire on\stepcounter, not on\setcounter.
Questions about this lesson
What is the difference between stepcounter and refstepcounter?
\stepcounter increments the register and resets its children. \refstepcounter does the same and additionally stores the current printed form in \@currentlabel (plus \@currentHref and \@currentcounter), which is the string a following \label records. If anything will ever \ref your counter, it has to be \refstepcounter.How do I make a counter reset when a section starts?
\newcounter{foo}[section] at declaration time, or \counterwithin{foo}{section} afterwards. The kernel form added in 2018 does both jobs \counterwithin also redefines \thefoo as \thesection.arabic(foo) so the printed number carries the section prefix; \newcounter only registers the reset. On old installations load chngcntr for the same two commands.Can I number my own environment without amsthm?
\newcounter{exercise}[section], \renewcommand{\theexercise}{\thesection.\arabic{exercise}}, and a \newenvironment whose start code calls \refstepcounter{exercise} and typesets \textbf{Exercise \theexercise.}. amsthm adds conveniences such as shared counters, styles and the optional name argument, not magic.What does usecounter do in a list?
\begin{list} it declares which counter \item steps and which counter an internal \label refers to. Its definition ends with \setcounter{#1}\z@, so it also zeroes that counter when the list starts.Why is my custom counter missing from the PDF bookmarks or links?
\theH<counter>, and the default is the bare integer, which collides between chapters. Redefine it more specific, e.g. \renewcommand{\theHexercise}{\thechapter.\arabic{exercise}}, and watch the log for duplicate-destination warnings.How do I make \ref print a different string from the heading?
\the<counter> only when the label value is written, so \thesolution can stay short on the page while \ref{sol:x} comes out with the section prefix attached. Keep one layer responsible for the noun, or \autoref will print it twice.Live playground: edit the LaTeX, see it render
The preview updates as you type — break it on purpose to see how errors look.
Keep reading
Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.