# Why does an environment's label have to appear after the caption?

\documentclass{article}
\usepackage{algorithm}

\begin{document}
\setcounter{section}{54}
\section{A section with no label}
\begin{algorithm}
\label{myalg}
\caption{An algorithm with the label `myalg'.}
\end{algorithm}
Reference to myalg: \ref{myalg}.
\end{document}

With this code, the reference givens 55 (the section number); if I move the label after the caption command, I get the correct reference (1).

Why should this be the case? I find it confusing: when thinking about an algorithm as an environment, you expect to be able to label it right after you began it. At the very least I would expect some kind of error or "??" to appear, rather than the previous environment or reference-able entity being used.

-

This is in common with all captions: it's the \caption command that generates the number, so a \label before it can't know that number.

This could have been designed differently, of course, but you can think to a figure environment where two figures with distinct captions are placed, side by side in order to save space, for example.

So, always place the \label after the \caption.

Since \label is a "general purpose" command, it will always refer to the last previously generated number (be it a chapter, section, figure caption number or directly from the user with a \refstepcounter command) and to the page where it eventually falls. Actually it's not really the last generated number, but the one lastly generated at the same or higher grouping level.

-
This example you give about figures is even more unintuitive: A single figure environment really has multiple figures. So a figure is not a figure, and you reference the caption instead of referencing the figure... also, in an algorithm environment you don't have that; I mean, maybe I can somehow have two algorithmics in there, but I would only reference the entire algorithm... –  einpoklum Oct 22 '11 at 8:57
@EyalRozenberg The example was just to explain the rationale for the programmer's choice. An algorithm environment doesn't generate a number; it's the \caption that does it: maybe you won't, but someone else might want to keep together two algorithmic environments (each one with its caption), to show the differences between them, for instance. –  egreg Oct 22 '11 at 9:03
When someone asks me why the label has to be after something and not before I always answer: "Well, the label of a bottle is also on it's outside and not on it's inside to make sense." –  Foo Bar Mar 8 '13 at 19:19