2

Is it possible to define a command \mycounter{<par>} in LaTeX which does the following:

  • if a counter with name <par> exists then increment the value of that counter and print the counter's current value;
  • if no counter with name <par> exists then create a new counter named <par> with value 1 and print the current value of <par>?
  • Defining counters on the fly is not always a good idea – user31729 Nov 24 '15 at 17:16
3

This generates the counter on the fly although this is not recommended in any case.

If the counter name given as first argument already exists, there is a command \c@#1 already which is LaTeX representation of a counter (well, top layer on \count.... registers actually.

If \@undefined{c@#1} is true, define the new counter and set it to one, displaying with \csname the#1\endcsname, i.e. \thefoo for example

\documentclass{article}

\makeatletter
\newcommand{\counteronthefly}[1]{%
  \@ifundefined{c@#1}{%
    \newcounter{#1}%
    \setcounter{#1}{1}%
    \csname the#1\endcsname% print it
  }{%
    \stepcounter{#1}%
    \csname the#1\endcsname% print it
  }%
}
\makeatother

\begin{document}
\parindent=0pt
\section{First}

section counter exist -- increase and show: \counteronthefly{section}

foo counter does not exist -- define, set to zero and show: \counteronthefly{foo}

foo counter does exist now -- increase and show: \counteronthefly{foo}


\end{document}

enter image description here

|improve this answer|||||
  • Since you already have @ a letter you can use \@nameuse{the#1} instead of \csname the#1\endcsname – cgnieder Nov 24 '15 at 17:33
  • @clemens: I rarely use \@nameuse -- it's a command out of my everyday's need – user31729 Nov 24 '15 at 17:42
  • Thanks! Is there a reason why you say generating counters on the fly is not good practice? – Ubiquitous Nov 24 '15 at 17:52
  • @Ubiquitous: There might be occasions where the generation on the fly might screw up the counter register system – user31729 Nov 24 '15 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.