# Defining TeX count in a group

I thought that TeX counts were local definitions, but that is not what I am seeing. I was expecting that if I used \newcount within a group, that the etoolbox \ifdefcounter would say that the counter is not defined outside the group. The following code produces:

\documentclass{minimal}

\usepackage{etoolbox}
\begin{document}
\ifdefcounter{\mycount}{The counter is defined}{The counter is NOT defined}

\begingroup
\newcount\mycount
\endgroup
\ifdefcounter{\mycount}{The counter is defined}{The counter is NOT defined}
\end{document}


The counter is NOT defined

The counter is defined

Suggesting to me that the counter is not defined at the beginning, but its existence persistence outside the group and hence is not local.

• Local allocation is as the answers indicate quite possible, but as TeX grouping is very different from that in other languages I'd recommend against it. We experimented with local registers in expl3, but they were more confusing than helpful. – Joseph Wright Mar 25 '13 at 12:43

If you want to allocate local counters, then you can use etex.sty:

\documentclass{article}
\usepackage{etex}

\usepackage{etoolbox}
\begin{document}
\ifdefcounter{\mycount}{The counter is defined}{The counter is NOT defined}

\begingroup
\loccount\mycount
\the\mycount

\texttt{\meaning\mycount}
\endgroup

\ifdefcounter{\mycount}{The counter is defined}{The counter is NOT defined}
\end{document}


Of course a LaTeX like syntax with \stepcounter and so on is out of the question, as these commands are global. One might define local versions of them, but I doubt about their usefulness.

Plain and LaTeX register allocations are global. You should just allocate a few registers globally at the start and re-use them as necessary, not allocate them within local groups.

• I am not sure what this means. Are you suggesting that I do \newcount outside the group? Wouldn't I then have to do something like \mycount 0\relax within the group? – StrongBad Mar 25 '13 at 15:31
• @DanielE.Shub You should do \newcount outside of the document body altogether, you should never dynamically use \new... macros in plain or latex they are just not designed for that. If your package needs three count registers it should have three \newcount commands you never need to do repeated allocations within a group, you just repeatedly assign values to the same register. Exactly yes you assign \mycount0  or whatever other values you need, you don't re-allocate the \mycount register. – David Carlisle Mar 25 '13 at 16:38
• @DanielE.Shub well never is too strong if you are defining a new allocation macro like \newtheorem then it makes sense for that to internally allocate a count, but then that command itself should only be used globally in the preamble. – David Carlisle Mar 25 '13 at 16:40