# Why to store a number via chardef?

For example, in plain.tex and in hyrules.tex (package hyplain) we find such code:

\chardef\active=13 \catcode\~=\active

\chardef\myh@us@catcode=\the\catcode\_
...
\catcode\_=\myh@us@catcode


Are there any other ways to store a number and why this way is preferable to others?

This trick spares on tokens and avoids problems with termination of constants.

For instance, LaTeX has \chardef\@ne=1 and \mathchardef\@M=10000; memory is less cluttered if \penalty\@M is stored instead of

\def\nobreak{\penalty10000 }


(note the extra space, see How to use active character properly? for an example of where this space is important).

Note also that \penalty\@M is already finished and TeX will not look for a space token to remove, because \@M is unexpandable.

In your case, it would be the same doing

\edef\myh@us@catcode{\the\catcode\_ }
...
\catcode\_=\myh@us@catcode


Also \def\active{13 } would be a substitute of \chardef\active=13, but using the latter avoids expansion problems.

However, the first line of the code you show should better be

\chardef\myh@us@catcode=\catcode\_


because the \the serves no purpose: when TeX is looking for a <number>, primitives such as \catcode, \lccode and similar are allowed and will return the value, without the extra step of converting it into its decimal representation.

And, yes: I'm the author of hyplain. :-) A slip. ;-)

It is traditional to store such numbers as \chardef (or \mathchardef to get a larger range) eg plain tex has

\chardef\@ne=1
\chardef\tw@=2
\chardef\thr@@=3
\chardef\sixt@@n=16
\chardef\@cclv=255
\mathchardef\@cclvi=256
\mathchardef\@m=1000
\mathchardef\@M=10000
\mathchardef\@MM=20000


This stores the number as a single token so it is more efficient in space and time than say

\def\@cclv{255 }


an alternative would be a count register but in classic TeX there are only 256 registers of each type so they are a scarce resource.