2

I would like to define and use a variable in my title page. This variable depends on the contents of the entire document. For illustration purposes, the variable could be a counter that is incremented throughout the document. When the document is compiled I want the variable to contain the total value of all increments in the document---even when it is used at the beginning of the document. That is, I want to sum all increments at the beginning of the file.

For example, something like this

\documentclass{article}
\newcommand\x{0}
\begin{document}

\sumOfAllIncrements
\incrementX
\sumOfAllIncrements
\incrementX
\incrementX
\sumOfAllIncrements

\end{document}

Needs to output

3
3
3

Does anyone have any suggestions?

1
  • You should consider the totcount package
    – egreg
    Jul 14, 2016 at 19:50

1 Answer 1

2

There is no real need to use refcount, but it allows you to perform calculations with the reference, if that's needed.

\documentclass{article}

\usepackage{refcount}

\newcounter{Xcntr}
\newcommand{\incrementX}{\stepcounter{Xcntr}}% Increment Xcntr
\newcommand{\sumOfAllIncrements}{\getrefnumber{Xcntr}}% Retrieve Xcntr
\makeatletter
\AtEndDocument{\edef\@currentlabel{\theXcntr}\label{Xcntr}}% Update reference and \label it
\makeatother

\begin{document}

\sumOfAllIncrements

\incrementX

\sumOfAllIncrements

\incrementX

\incrementX

\sumOfAllIncrements

\end{document}
2
  • Well! That was certainly fast and effective!
    – Austin A.
    Jul 14, 2016 at 20:36
  • I've adapted your idea to my particular use. It works perfectly. Many thanks!
    – Austin A.
    Jul 14, 2016 at 20:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .