[Tex/LaTex] How do counts differ from numexpr

arithmeticcounterspackage-writingtex-core

To do basic arithmetic on numbers, one can utilize TeX counts,

\newcount\c
\c=2
\advance\c 3
\typeout{\the\c}

LaTeX counters

\newcounter{c}
\setcounter{c}{2}
\addtocounter{c}{3}
\typeout{\thec}

or the \numexpr macro.

\edef\c{\numexpr 2 + 5 \relax}
\typeout{\the\c}

Apart from their syntax, how do they differ? Which use cases are they most suitable for? Are there differences in performance? Which should be preferred for basic integer arithmetic as demonstrated in the examples above?

Best Answer

TeX has a fixed number (256 in classic TeX 32768 in etex and xetex and 65536 in luatex) of registers which store integer values.

\newcount\c allocates the name \c to one of these registers, and classic TeX primitives like \advance operate on them, note that addition here involves assignment back to the register so it is not an expandable operation.

LaTeX's \newcounter can be viewed as a syntactic wrapper around \newcount. \newcounter{abc} allocates the name \c@abc to a primitive TeX register allocated with \newcount. However as is often the case the extra layer of abstraction gives some useful features, notably that subsidiary macros are defined such as \theabc which defines the print form, and the counter is placed on reset lists so that for example incrementing section automatically sets subsection to zero. A similar list is used to preserve counters for the \include mechanism.

TeX primitive operations may be local or global

\c=2 { \advance\c 1 } \the\c

will produce 2 as the increment will be lost at the }

\c=2 { \global\advance\c 1 } \the\c

will produce 3 as the global assignment will be seen at all grouping levels.

LaTeX counter assignments are always global which reflects their top level use as for example a figure counter, the caption is typically inside a box which forms a group but you want the counter to have global document scope.

This means you often see primitive register use for local "scratch" arithmetic and latex counters for top level structural document counters.

\numexpr is an e-tex extension which gives (more or less) the same arithmetic operations as the \advance, \multiply etc primitives, but is classified as an expandable operation and does not automatically assign the value back to a register.

Because it is expandable it works in an \edef as shown in your (corrected)

\edef\c{\the\numexpr 2 + 5 \relax}

 \show\c

example.