Not sure how I should post my question but here it is: I've seen that in plain TeX, \newcount is illegal inside a macro \definition. Is there a way to allocate a register inside a macro? Also, if I know that I will use a register only once or twice, can I free it after and leave the space for a future \newcount?

It is not illegal, it works: it is just usually a bad idea, you should allocate the counter once and then use it each time in the macro. But if you want do it it works in particular if you are defining a variant declaration form (eg declaring a theorem needs to declare a counter.
–
David CarlisleJan 16 '14 at 15:24

2 Answers
2

In Plain TeX, \newcount is defined as \outer so it can't be in the replacement text for a macro. The idea is that a macro should never define a new counter, although this isn't true in every occasion, but I'll do an example later.

The main reason for this is that you can't "free" the register after having allocated it. I could be possible, but what about other macros that might have defined to access it? The best strategy is to use symbolic names (what \newcount does) and never care about the actual register number.

If you need a counter for temporary storage, just use \count255 (which is aliased to \count@) or, in a group, any other count register. In more complex cases you can allocate a temporary counter yourself and use it as many times as you wish.

Here's an example of a “legitimate” call of \newcount in a definition. Suppose you want to define distinct counters for different logical structures (like LaTeX does for \newtheorem). So you want to define a command

Thanks! I'll review the expansion rules more closely. Btw it could be possible to define \freecount, \freeskip etc for TeX if \newcount were redefined to allocate a number in function of the previously free'd registers, am I right?
–
lvaneesbeeckJan 16 '14 at 15:54

@lvaneesbeeck Not really. One would have to maintain a catalog of the allocation numbers and of the associated names. But you can always say \newcount\foo and then \let\baz\foo and this would give headaches, at the least.
–
egregJan 16 '14 at 15:57

However it is almost always better not to do this and to allocate the counter once, amd just use it in each macro.

I assume that you mean LaTeX (as you used \newcounter) If on the other hand you mean the plain TeX \newcount that is different as it is an \outer macro to stop you using it.
It is possible to work around that, However the same applies that it is almost always better not to do so.

the standard allocation system used in plain and latex does not allow for freeing unused allocations. It is a simple increment. In classic TeX there are only 256 count registers so you can easily run out, etex allows several thousand so it is less of a problem there.