GeneralDefining a new counter conditional on it being undefined

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
leo simon
Posts: 17
Joined: Wed Aug 19, 2009 5:41 pm

Defining a new counter conditional on it being undefined

Post by leo simon »

I have a counter that has been defined in two packages. One is a general
purpose package that I input into all my files, the other is a special purpose
one used just for one document. I want to be able to check in the latter
package to see if the counter has been defined. That is, I'd like to do
something like

Code: Select all

\ifx\mycounter\undefined
    \newcounter{mycounter}
\fi
But this syntax doesn't work for counters

Any advice would be most appreciated

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

sommerfee
Posts: 503
Joined: Mon Apr 09, 2007 4:20 pm

Defining a new counter conditional on it being undefined

Post by sommerfee »

leo simon wrote:But this syntax doesn't work for counters
A counter defined with \newcounter will be defined with the prefix c@ internally. Doing so one can define counters and environments resp. commands with the same name, e.g. "section" (there is a \section command and a "section" counter related to it), "figure" (there is a "figure" environment and a counter related to it) etc.

So try

Code: Select all

\ifx\c@mycounter\undefined
 \newcounter{mycounter}
\fi
instead.
leo simon
Posts: 17
Joined: Wed Aug 19, 2009 5:41 pm

Re: Defining a new counter conditional on it being undefine

Post by leo simon »

Thanks very much for this. have only just login in again and seen your response after many months!
talion
Posts: 1
Joined: Fri Oct 18, 2013 2:58 pm

Defining a new counter conditional on it being undefined

Post by talion »

I run into a problem using this solution, but could fix it using a proposal shown on StackOverflow. Before using @ in the label name, it's necessary (at least in my setup) to use \makeatletter before and \makeatother afterwards. With this additional step, the solution works for me.
Last edited by talion on Fri Oct 18, 2013 6:23 pm, edited 1 time in total.
User avatar
cgnieder
Site Moderator
Posts: 2000
Joined: Sat Apr 16, 2011 7:27 pm

Defining a new counter conditional on it being undefined

Post by cgnieder »

talion wrote:... before using it in the label name, it's necessary (at least in my setup) to use \makeatletter before and \makeatother afterwards.
That's correct if used in the preamble of a document. In a package file such as stated in the question the use of \makeatletter and \makeatother is not needed and in fact even wrong

Regards
site moderator & package author
Post Reply