Frequently Asked Question List for TeX


Master and slave counters

It’s common to have things numbered “per chapter” (for example, in the standard book and report classes, figures, tables and footnotes are all numbered thus). The process of resetting is done automatically, when the “master” counter is stepped (when the \chapter command that starts chapter ‹n› happens, the chapter counter is stepped, and all the dependent counters are set to zero).

How would you do that for yourself? You might want to number algorithms per section, or corollaries per theorem, for example. If you’re defining these things by hand, you declare the relationship when you define the counter in the first place: \newcounter{new-name}[master] says that every time counter ‹master› is stepped, counter ‹new-name› will be reset.

But what if you have an uncooperative package, that defines the objects for you, but doesn’t provide a programmer interface to make the counters behave as you want?

The \newcounter command uses a LaTeX internal command, and you can also use it: \@addtoreset{new-name}{master} (but remember that it needs to be between \makeatletter and \makeatother, or in a package of your own).

The chngcntr package encapsulates the \@addtoreset command into a command \counterwithin. So:


will make the corollary counter slave to theorem counters. The command without its asterisk:


will do the same, and also redefine \thecorollary as ‹theorem number›.‹corollary number›, which is a good scheme if you ever want to refer to the corollaries — there are potentially many “corollary 1” in any document, so it’s as well to tie its number to the counter of the theorem it belongs to. This is true of pretty much any such counter-within-another; if you’re not using the chngcntr, refer to the answer to redefining counters’ \the-commands for the necessary techniques.

The 2018 LaTeX release adopted the chngcntr commands into the format, so \counterwithin and \counterwithout are now directly available without requiring a package.

Note that the technique doesn’t work if the master counter is page, the number of the current page. The page counter is stepped deep inside the output routine, which usually gets called some time after the text for the new page has started to appear: so special techniques are required to deal with that. One special case is dealt with elsewhere: footnotes numbered per page. One of the techniques described there, using package perpage, may be applied to any counter. The command: \MakePerPage{counter} will cause ‹counter› to be reset for each page. The package uses a label-like mechanism, and may require more than one run of LaTeX to stabilise counter values — LaTeX will generate the usual warnings about labels changing.

FAQ ID: Q-addtoreset
Tags: latexmacros