# How can I access and store the current value of a counter?

My counter is being updated by a command and I want to save the current value + 1 of this counter at a specific point so that later on I am able to print it out.

\newcounter{counterA}
\newcounter{tempcounter}

\def\storevalue#1{
\setcounter{tempcounter}{\value{counterA}}
\refstepcounter{tempcounter}

\def\tempA{\arabic{tempcounter}}
\let\tempB\tempA

\expandafter\def\csname data:\string#1\endcsname{\textbf{Value \tempB}}%
}

\def\getvalue#1{\csname data:\string#1\endcsname}


And in the body of my document I would have something like

\refstepcounter{counterA}
\storevalue\vala
\refstepcounter{counterA}
\refstepcounter{counterA}
\storevalue\valb
\refstepcounter{counterA}
\storevalue\valc

\getvalue\vala

\getvalue\valc

\getvalue\valb


And I would like this to be the output in the pdf

Value 2

Value 5

Value 4

• Welcome to TeX.SE! Please make your code snippets compilable! That means start with \documentclass and end the tex code with \end{documentation} ... – Mensch Feb 14 '19 at 6:47
• See the answers to this question: tex.stackexchange.com/q/164069/172926 – Pippip19 Feb 14 '19 at 6:55

No need for 'weird' 'expansion', the tools of storage are already there if \label is used and \getrefnumber from refcount package if expandable retrieving is required, otherwise fall back to \ref instead of \getrefnumber.

\documentclass{article}
\usepackage{refcount}

\newcounter{counterA}
\newcounter{tempcounter}

\newcommand{\storevalue}[1]{%
\setcounter{tempcounter}{\value{counterA}}%
\refstepcounter{tempcounter}\label{#1}%
}

\newcommand{\getvalue}[1]{\getrefnumber{#1}}

\begin{document}

\refstepcounter{counterA}% Should be 1 now
\storevalue{vala}% Store 2
\refstepcounter{counterA}
\refstepcounter{counterA}
\storevalue{valb}% Store 4
\refstepcounter{counterA}
\storevalue{valc} % Store 5

\getvalue{vala} % 2

\getvalue{valc} % 5

\getvalue{valb} % 4

\end{document}

• @UlrichDiez: The counter is set temporarily set, as you can see, then \refstepped, i.e. if initially 7, the new value is 8, which is stored to the label as well. The output of my solution is exactly what the O.P. wants. – user31729 Feb 16 '19 at 17:41
• In some situation a problem might be that \storevalue does change \@currentlabel to the value of the scratch-counter tempcounter permanently. Perhaps calling \refstepcounter and \label should take place within a local scope/group.(When loading the hyperref package also, you will get anchors for hyperlinking to the place in the document that corresponds to the place where tempcounter was refstepped whenever \storevalue is used. \@currentHref will be changed globally as that is done by the package in terms of a \global-assignment...) – Ulrich Diez Feb 16 '19 at 19:29
• @UlrichDiez: Such cases may come in if hyperref is used -- but there is no information on that, as such I don't change my answer. – user31729 Feb 16 '19 at 19:40
• The permanent change to \@currentlabel due to refstepping a scratch-counter (tempcounter) also happens without hyperref. – Ulrich Diez Feb 16 '19 at 20:09

Something like this? I expanded the stored value rather than just assigning a macro to it that changes.

\documentclass{article}
\newcounter{counterA}

\def\storevalue#1{

\edef\tempA{\the\numexpr\value{counterA}+1}

\expandafter\edef\csname data:\string#1\endcsname{\noexpand\textbf{Value \tempA}}%
}

\def\getvalue#1{\csname data:\string#1\endcsname}

\begin{document}
\refstepcounter{counterA}
\storevalue\vala
\refstepcounter{counterA}
\refstepcounter{counterA}
\storevalue\valb
\refstepcounter{counterA}
\storevalue\valc

\getvalue\vala

\getvalue\valc

\getvalue\valb
\end{document}


• Maybe it would be a little more elegant to put \textbf in \getvalue (without that \noexpand). – zetaeffe Feb 14 '19 at 6:59
• @zetaeffe Well, then it would be a bit pointless IMHO, the answer is not so much about printing some boldface texts but about \edef vs. \def and there it is important to know the \noexpand thingy for more delicate applications. – user121799 Feb 14 '19 at 7:04
• Ok, you're right. – zetaeffe Feb 14 '19 at 7:06
• @marmot Why do you use two \edef ? The things that go into the \edef for \tempA could go into the \edef for \csname data:\string#1\endcsname directly. – Ulrich Diez Feb 14 '19 at 8:36
• I'm not sure you want to issue two \par commands at each usage of \storevalue. – egreg Feb 14 '19 at 22:28

Beware of endlines and blank lines in definitions.

You're doing unnecessary assignments and miss the crucial expansion when you define \data:<name>.

I avoided pseudo-control sequences, preferring plain names, but it's up to you.

\documentclass{article}

\newcounter{counterA}
\newcounter{tempcounter}

\newcommand\storevalue[1]{%
\setcounter{tempcounter}{\value{counterA}}%
\stepcounter{tempcounter}%
% the following must be \edef or \protected@edef if you have
% more material that would fail in \edef such as \textbf
\expandafter\edef\csname data:#1\endcsname{%
\noexpand\textbf{Value \arabic{tempcounter}}%
}%
}
\newcommand\getvalue[1]{\csname data:#1\endcsname}

\begin{document}

\refstepcounter{counterA}
\storevalue{vala}
\refstepcounter{counterA}
\refstepcounter{counterA}
\storevalue{valb}
\refstepcounter{counterA}
\storevalue{valc}

\getvalue{vala}

\getvalue{valc}

\getvalue{valb}

\end{document}


For the sake of having fun I offer a variant which makes use of ε-TeX's expressions of type number and where expansion/evaluation of such an expression is not triggered via \edef but via cascades of \romannumeral-expansion and exchanging arguments. (The picture below is borrowed from egreg's answer as the results with our answers look the same.)

\documentclass{article}

\newcounter{counterA}

\newcommand\MYNAMESPACEexchange[2]{#2#1}%

% In case you trust in \storevalue's argument not containing mean
% things like \GobbleToEndcsnameAndInsertEndcsname with
%
%   \long\def\GobbleToEndcsnameAndInsertEndcsname#1\endcsname{\endcsname}
%
% , which would, e.g., remove an \expandafter in front of
% \endcsname, you can do:
%
%\newcommand\storevalue[1]{%
%  \expandafter\def\csname data:#1\expandafter\endcsname
%  \expandafter{%
%    \expandafter\textbf\expandafter{%
%      \romannumeral0%
%      \MYNAMESPACEexchange{ }{\expandafter\expandafter\expandafter}%
%      \expandafter\MYNAMESPACEexchange
%      \expandafter{\the\numexpr\arabic{counterA}+1\relax}{Value }%
%    }%
%  }%
%}%
%
% If you don't trust in that, then do:
%
\newcommand\storevalue[1]{%
\expandafter\MYNAMESPACEexchange\expandafter{\expandafter{%
\romannumeral0%
\MYNAMESPACEexchange{ }{\expandafter\expandafter\expandafter}%
\expandafter\MYNAMESPACEexchange\expandafter{\expandafter{%
\romannumeral0%
\MYNAMESPACEexchange{ }{\expandafter\expandafter\expandafter}%
\expandafter\MYNAMESPACEexchange
\expandafter{\the\numexpr\arabic{counterA}+1\relax}{Value }%
}}{\textbf}%
}}{\expandafter\def\csname data:#1\endcsname}%
}%
\newcommand\getvalue[1]{\csname data:#1\endcsname}

\begin{document}

\refstepcounter{counterA}
\storevalue{vala}
\refstepcounter{counterA}
\refstepcounter{counterA}
\storevalue{valb}
\refstepcounter{counterA}
\storevalue{valc}

%\expandafter\show\csname data:vala\endcsname
\getvalue{vala}

%\expandafter\show\csname data:valc\endcsname
\getvalue{valc}

%\expandafter\show\csname data:valb\endcsname
\getvalue{valb}

\end{document}


For saving counter-values and retrieving them throughout the entire document, the LaTeX 2ε-kernel provides the \label-\ref-mechanism. Heiko Oberdiek's package refcount provides means for retrieving things expandably if this is needed.

But all these things are restricted to saving and retrieving values of counters that were stepped by the \refstepcounter-command.

Saving and retrieving an arbitrary ⟨number⟩ can be implemented by means of Heiko Oberdiek's package zref.

What a ⟨number⟩ is is elaborated in the TeXbook, Chapter 24: Summary of Vertical Mode and in The ε-TeX manual, section 5.1 Mode-Independent Commands.

A ⟨number⟩ does not necessarily need to come from a LaTeX counter.

A ⟨number⟩ can, e.g., also be the result of evaluating an expression of type number, i.e., a \numexpr-construct. \numexpr can be used for calculations. Expressions like \numexpr are explained in The ε-TeX manual, section 3.5 expressions.

The example below provides the following macros:

\StoreNumber{⟨label⟩}%
{⟨number⟩}

\StoreNumber evaluates ⟨number⟩ and creates a zref-referencing-label whose name is ⟨label⟩ for retrieving the result of that evaluation.

\StorePrefixAndNumberAndPostfix{⟨label⟩}%
{⟨prefix phrase⟩}%
{⟨number⟩}%
{⟨postfix phrase⟩}

\StorePrefixAndNumberAndPostfix evaluates ⟨number⟩ and creates a zref-referencing-label whose name is ⟨label⟩ for retrieving the result of that evaluation. By means of the same zref-referencing-label you can also retrieve ⟨prefix phrase⟩ and ⟨postfix phrase⟩. The two phrases get stored in "detokenized fashion". I.e., they will not be expanded/evaluated at the time of creating the zref-referencing-label.

\RetrieveNumber{⟨label⟩}

\RetrieveNumber retrieves the ⟨number⟩ associated to the zref-referencing-label ⟨label⟩.

\RetrievePrefix{⟨label⟩}

\RetrievePrefix retrieves the ⟨prefix phrase⟩ associated to the zref-referencing-label ⟨label⟩.

\RetrievePostfix{⟨label⟩}

\RetrievePostfix retrieves the ⟨postfix phrase⟩ associated to the zref-referencing-label ⟨label⟩.

\RetrievePrefixAndNumberAndPostfix{⟨label⟩}

\RetrievePrefixAndNumberAndPostfix retrieves

• the ⟨prefix phrase⟩ associated to the zref-referencing-label ⟨label⟩
• the ⟨number⟩ associated to the zref-referencing-label ⟨label⟩
• the ⟨postfix phrase⟩ associated to the zref-referencing-label ⟨label⟩.

In terms of these macros, you can, e.g., define macros

\storevalue{⟨label⟩}

and

\getvalue{⟨label⟩}

for saving and retrieving specifically the result of incrementing the value of counterA by 1:

\DeclareRobustCommand\storevalue[1]{%
\StoreNumber{#1}{\the\numexpr\value{counterA}+1\relax}%
}%
\DeclareRobustCommand\getvalue[1]{\textbf{Value \RetrieveNumber{#1}}}%

As with everything related to the \label-\ref-mechanism it takes at least two LaTeX-runs until everything turns out correctly.

\documentclass[landscape]{article}

%--<stuff only needed for making the example looking good>-----------------
\usepackage{textcomp}
\usepackage{amstext}
\expandafter\ifx\csname pdfpagewidth\endcsname\relax\else
\pdfpagewidth=\paperwidth
\pdfpageheight=\paperheight
\fi
\expandafter\ifx\csname pagewidth\endcsname\relax\else
\pagewidth=\paperwidth
\pageheight=\paperheight
\fi
\textwidth=\paperwidth
\oddsidemargin=1cm
\evensidemargin=\oddsidemargin
\textheight\paperheight
\topmargin=1cm
\pagestyle{empty}%
\parindent=0ex
\parskip=\medskipamount
\newenvironment{makeverbatimnice}{\topsep=0ex\partopsep=0ex\ignorespaces}{}%
\newcommand\ThingsName[1]{\textsf{#1''}}%
\newcommand\meta[1]{\textit{\textlangle#1\textrangle}}%
%--<eof stuff only needed for making the example looking good>-------------
%
%--<stuff needed for implementing the user-macros>-------------------------
\usepackage{zref}
\makeatletter
% My variant of \@bsphack / \@esphack.
\newskip\MYNAMESPACE@savsk
\newcommand*\MYNAMESPACE@bsphack{%
\relax
\ifhmode\MYNAMESPACE@savsk\lastskip\@savsk\lastskip\@savsf\spacefactor\fi
}%
\newcommand*\MYNAMESPACE@esphack{%
\relax
\ifhmode
\spacefactor\@savsf
\ifdim\@savsk>\z@
\ifdim\lastskip=\z@\nobreak\hskip\z@skip\fi
% The following \hskips are used for restoring \lastskip.
% I hope there are no evil side-effects. ;-)
\nobreak\hskip-\MYNAMESPACE@savsk
\nobreak\hskip\MYNAMESPACE@savsk
\ignorespaces
\fi
\fi
}%
%
\newcommand\MYNAMESPACE@Exchange[2]{#2#1}%
%
\AtBeginDocument{%
\DeclareRobustCommand\MYNAMESPACE@RefUndefText{%
\texorpdfstring{\nfss@text{\reset@font\bfseries ??}}{??}%
}%
}{%
\DeclareRobustCommand\MYNAMESPACE@RefUndefText{%
\nfss@text{\reset@font\bfseries ??}%
}%
}%
}%
%
\zref@newprop{numbertostore}[0]{0}
\zref@newprop{numberprefix}[]{}
\zref@newprop{numberpostfix}[]{}
%
\DeclareRobustCommand\StorePrefixAndNumberAndPostfix[4]{%
\MYNAMESPACE@bsphack
\begingroup
\zref@setcurrent{numberprefix}{\detokenize{#2}}%
\zref@setcurrent{numberpostfix}{\detokenize{#4}}%
\expandafter\MYNAMESPACE@Exchange\expandafter{%
\expandafter{\the\numexpr\number#3\relax}%
}{%
\zref@setcurrent{numbertostore}%
}%
\zref@wrapper@immediate{%
\zref@labelbyprops{#1}{numbertostore,numberprefix,numberpostfix}%
}%
\endgroup
\MYNAMESPACE@esphack
}%
\DeclareRobustCommand\StoreNumber[2]{%
\MYNAMESPACE@bsphack
\begingroup
\expandafter\MYNAMESPACE@Exchange\expandafter{%
\expandafter{\the\numexpr\number#2\relax}%
}{%
\zref@setcurrent{numbertostore}%
}%
\zref@wrapper@immediate{%
\zref@labelbyprops{#1}{numbertostore}%
}%
\endgroup
\MYNAMESPACE@esphack
}%
\DeclareRobustCommand\RetrieveNumber[1]{%
\zref@refused{#1}%
\zref@extractdefault{#1}{numbertostore}{\MYNAMESPACE@RefUndefText}%
}%
\DeclareRobustCommand\RetrievePrefix[1]{%
\zref@refused{#1}%
\zref@extractdefault{#1}{numberprefix}{\MYNAMESPACE@RefUndefText}%
}%
\DeclareRobustCommand\RetrievePostfix[1]{%
\zref@refused{#1}%
\zref@extractdefault{#1}{numberpostfix}{\MYNAMESPACE@RefUndefText}%
}%
\DeclareRobustCommand\RetrievePrefixAndNumberAndPostfix[1]{%
\zref@refused{#1}%
\zref@extractdefault{#1}{numberprefix}{}%
\zref@extractdefault{#1}{numbertostore}{\MYNAMESPACE@RefUndefText}%
\zref@extractdefault{#1}{numberpostfix}{}%
}%
\makeatother
%--<eof stuff needed for implementing the user-macros>---------------------

\newcounter{counterA}
\newcounter{counterB}

\begin{document}

\hbox to\textwidth{\null\hrulefill\null}%

The \meta{number} stored as \ThingsName{First Stored Number} is retrieved
via \verb|\RetrieveNumber{First Stored Number}|:
\RetrieveNumber{First Stored Number}%

The prefix associated with the \meta{number} stored as
\ThingsName{Second Stored Number} is retrieved via
\verb|\RetrievePrefix{Second Stored Number}|:
\RetrievePrefix{Second Stored Number}%

The \meta{number} stored as \ThingsName{Second Stored Number} is retrieved
via \verb|\RetrieveNumber{Second Stored Number}|:
\RetrieveNumber{Second Stored Number}%

The postfix associated with the \meta{number} stored as
\ThingsName{Second Stored Number} is retrieved via
\verb|\RetrievePostfix{Second Stored Number}|:
\RetrievePostfix{Second Stored Number}%

Everything associated with the \meta{number} stored as
\ThingsName{Second Stored Number} is retrieved via
\verb|\RetrievePrefixAndNumberAndPostfix{Second Stored Number}|:\\
\RetrievePrefixAndNumberAndPostfix{Second Stored Number}

\hbox to\textwidth{\null\hrulefill\null}%

\ThingsName{counterA} is set to 7.
\setcounter{counterA}{7}%

\ThingsName{counterB} is set to 14.
\setcounter{counterB}{14}%

\hbox to\textwidth{\null\hrulefill\null}%

A \meta{number} is stored as \ThingsName{First Stored Number} via
\begin{makeverbatimnice}
\begin{verbatim}
\StoreNumber{First Stored Number}%
{\the\numexpr\value{counterA}*\value{counterB}/2\relax}%
\end{verbatim}%
\end{makeverbatimnice}%
\StoreNumber{First Stored Number}%
{\the\numexpr\value{counterA}*\value{counterB}/2\relax}%

\emph{(The expression evaluates to 49 as
$$\text{\texttt{\string\value\string{counterA\string}}}% \cdot \text{\texttt{\string\value\string{counterB\string}}}\,/\,2% =7\cdot14\,/\,2=49$$.)}

A prefix phrase, a \meta{number} and a postfix phrase are stored
under \ThingsName{Second Stored Number} via
\begin{makeverbatimnice}
\begin{verbatim}
\StorePrefixAndNumberAndPostfix{Second Stored Number}%
{The number }%
{\the\numexpr\value{counterB}+3\relax}%
{ is a prime number.}%
\end{verbatim}%
\end{makeverbatimnice}%
\StorePrefixAndNumberAndPostfix{Second Stored Number}%
{The number }%
{\the\numexpr\value{counterB}+3\relax}%
{ is a prime number.}%

\emph{(The expression evaluates to 17 as
$$\text{\texttt{\string\value\string{counterB\string}}}+3=14+3=17$$.)}

\hbox to\textwidth{\null\hrulefill\null}%

The \meta{number} stored as \ThingsName{First Stored Number} is retrieved
via \verb|\RetrieveNumber{First Stored Number}|:
\RetrieveNumber{First Stored Number}%

The prefix associated with the \meta{number} stored as
\ThingsName{Second Stored Number} is retrieved via
\verb|\RetrievePrefix{Second Stored Number}|:
\RetrievePrefix{Second Stored Number}%

The \meta{number} stored as \ThingsName{Second Stored Number} is retrieved
via \verb|\RetrieveNumber{Second Stored Number}|:
\RetrieveNumber{Second Stored Number}%

The postfix associated with the \meta{number} stored as
\ThingsName{Second Stored Number} is retrieved via
\verb|\RetrievePostfix{Second Stored Number}|:
\RetrievePostfix{Second Stored Number}%

Everything associated with the \meta{number} stored as
\ThingsName{Second Stored Number} is retrieved via
\verb|\RetrievePrefixAndNumberAndPostfix{Second Stored Number}|:\\
\RetrievePrefixAndNumberAndPostfix{Second Stored Number}

\hbox to\textwidth{\null\hrulefill\null}%

\newpage

In terms of these macros you can, e.g., define macros \verb|\storevalue|
and \verb|\getvalue| for saving and retrieving specifically the result
of incrementing the value of \ThingsName{counterA} by 1:
\begin{makeverbatimnice}
\begin{verbatim}
\DeclareRobustCommand\storevalue[1]{%
\StoreNumber{#1}{\the\numexpr\value{counterA}+1\relax}%
}%
\DeclareRobustCommand\getvalue[1]{\textbf{Value \RetrieveNumber{#1}}}%
\end{verbatim}%
\end{makeverbatimnice}%
\DeclareRobustCommand\storevalue[1]{%
\StoreNumber{#1}{\the\numexpr\value{counterA}+1\relax}%
}%
\DeclareRobustCommand\getvalue[1]{\textbf{Value \RetrieveNumber{#1}}}%

\hbox to\textwidth{\null\hrulefill\null}%

\verb|\getvalue{vala}|: \getvalue{vala}%

\verb|\getvalue{valc}|: \getvalue{valc}%

\verb|\getvalue{valb}|: \getvalue{valb}%

\hbox to\textwidth{\null\hrulefill\null}%

\begin{makeverbatimnice}
\begin{verbatim}
\setcounter{counterA}{0}%
\stepcounter{counterA}% You can also use \refstepcounter but you don't have to.
\storevalue{vala}%
\stepcounter{counterA}% You can also use \refstepcounter but you don't have to.
\stepcounter{counterA}% You can also use \refstepcounter but you don't have to.
\storevalue{valb}%
\stepcounter{counterA}% You can also use \refstepcounter but you don't have to.
\storevalue{valc}%
\end{verbatim}%
\end{makeverbatimnice}%
\setcounter{counterA}{0}%
\stepcounter{counterA}% You can also use \refstepcounter but you don't have to.
\storevalue{vala}%
\stepcounter{counterA}% You can also use \refstepcounter but you don't have to.
\stepcounter{counterA}% You can also use \refstepcounter but you don't have to.
\storevalue{valb}%
\stepcounter{counterA}% You can also use \refstepcounter but you don't have to.
\storevalue{valc}%

\hbox to\textwidth{\null\hrulefill\null}%

\verb|\getvalue{vala}|: \getvalue{vala}%

\verb|\getvalue{valc}|: \getvalue{valc}%

\verb|\getvalue{valb}|: \getvalue{valb}%

\end{document}