[Tex/LaTex] \the vs. \value: what is the difference

counterstex-core

I would like to understand the difference between \the and \value{}
when using counters in LaTeX.

Best Answer

\thecounter typesets the result of the counter, be it in arabic, roman, etc, while \value{counter} provides an integer value in return. In many, but not all, instances, the difference will go unnoticed.

The rule is, if you are looking for a character, use \the...; if you are looking for an integer, use \value{...}.

Here's an example where it matters. By typesetting the page number in roman (via \pagenumbering{roman}), the option of \romannumeral\thepage is no longer an option, since it would be attempting \romannumeral i, whereas \romannumeral\value{page} works fine.

\documentclass{article}
\pagenumbering{roman}
\begin{document}
\romannumeral\value{page}

% \romannumeral\thepage will break
\end{document}

Here's another example...you cannot typeset \value

\documentclass{article}
\begin{document}

\newcounter{Q}
\setcounter{Q}{2}

%\value{Q} will break

\theQ
\end{document}

The difference can also affect comparisons, since \if compares tokens, not integers:

\documentclass{article}
\begin{document}

\newcounter{Q}
\setcounter{Q}{2}

\if\value{Q}2 T\else F\fi is false

\if\theQ2 T\else F\fi is true

\end{document}

The above example would show a match, were the \ifs changed to \ifnums, since \ifnum will interpret/convert the character 2 into an integer. However, even that can get you into trouble for more complex cases.

Here, I can combine \theQ with 3 to represent 23. The same does not apply for \value{Q}3.

\documentclass{article}
\begin{document}

\newcounter{Q}
\setcounter{Q}{2}

%\ifnum\value{Q}3=23 T\else F\fi will break

\ifnum\theQ3=23 T\else F\fi is true

\end{document}

Now this last one is quite unusual. That of using \value to try to provide the numerical part of a length specification. It works as expected if you merely specify \value{Q} pt. However, if you try 2\value{Q} pt, it takes the 2 as a multiplier and \value{Q} as a length specified in sp machine units! The trailing pt becomes an extraneous residual, not even part of the length.

This behavior occurs because, deep down in TeX, lengths are actually stored as integer counts in machine units. What value TeX uses as its minimal unit

\documentclass{article}
\def\q{\rule{2pt}{10pt}}
\begin{document}

\newcounter{Q}
\setcounter{Q}{2}

\q\hspace{\theQ pt}\q{} skips 2pt

\q\hspace{\value{Q} pt}\q{} skips 2pt

\q\hspace{1\theQ pt}\q{} skips 12pt

\setcounter{Q}{100000}

\q\hspace{2\value{Q} pt}\q{} skips 200000sp before reaching the ``pt''

\q\hspace{200000 sp}\q{} skips 200000sp for comparison
\end{document}

enter image description here