[Tex/LaTex] Why do \setcounter and \addtocounter commands have global effect, while \setlength and \addtolength commands obey the normal scoping rules

countersgroupinglengths

The \setcounter and \addtocounter commands have global effect,
while the \setlength and \addtolength commands obey the normal
scoping rules.

Why were they designed like this? Why are \setcounter and \addtocounter not defined to obey normal scoping rules?

Best Answer

That is by design and coded accordantly in the LaTeX core source code. Counters in LaTeX usually count things which are independent from the local group. For example figure captions are enclosed in the group added by the figure environment and any change to the figure counter used by the caption would be lost afterwards. This would render the counter mostly useless.

If you want to set a counter locally use \c@<counter name>=value. To add something to it use \advance\c@<counter name> by value. To build the counter macro you can use \csname name\endcsname or (mis-)use \value{name} which also works on the left hand side of an assignment.

You can also define an own counter using the TeX macro \newcount\yourcounter and then use \yourcounter=<value> etc. However, you then need to define the \theyourcounter macro yourself if you need it and can't use the normal counter formating macros like \arabic{..} or \roman{..} with it.

Related Question