# Reference algorithmic line numbers using cleveref

consider the following example:

\documentclass[a4paper,final]{report}

\usepackage{cleveref}
\usepackage{algorithmic}

\Crefname{ALC@unique}{Line}{Lines}

\begin{document}

Tests:

\begin{algorithmic}[1]
\REQUIRE $x$ and $y$
\ENSURE $|x + y|$
\STATE $z = x + y$
\IF{$z<0$}
\RETURN $-z$\label{l1}
\ELSE
\RETURN $z$
\ENDIF
\end{algorithmic}

cref\{l1\}: \cref{l1}, ref\{l1\}: \ref{l1}

\begin{algorithmic}[1]
\REQUIRE $x$ and $y$
\ENSURE $|x - y|$
\STATE $z = x - y$
\IF{$z<0$}
\RETURN $-z$\label{l2}
\ELSE
\RETURN $z$
\ENDIF
\end{algorithmic}

cref\{l2\}: \cref{l2}, ref\{l2\}: \ref{l2}

\end{document}


This will output (apart from the pseudocode):

cref{l1}: line 3, ref{l1} 3

cref{l2}: line 9, ref{l2} 3


As you will notice, \cref{l2} returns an incorrect line number. Any suggestions on how to fix this?

cleveref only claims to support a limited number of packages and algorithmic is not on that list. However, adding \setcounter{ALC@unique}{0} after the beginning of your algorithmic enviroments fixes the problem, i.e., writing

\begin{algorithmic}[1]
\setcounter{ALC@unique}{0}
\REQUIRE $x$ and $y$


etc.

I suggest you wrap this up in a new environment, so that you do not have to write it each time.

If you also want hyperref to behave properly, then I suggest packaging as follows

\documentclass[a4paper,final]{report}

\usepackage{algorithmic}
\usepackage{hyperref}
\usepackage{cleveref}

\Crefname{ALC@unique}{Line}{Lines}
\newcounter{myalg}
\AtBeginEnvironment{algorithmic}{\refstepcounter{myalg}}
\makeatletter
\makeatother

\begin{document}

Test 1

\begin{algorithmic}[1]
\REQUIRE $x$ and $y$
\ENSURE $|x + y|$
\STATE $z = x + y$
\IF{$z<0$}
\RETURN $-z$\label{l1}
\ELSE
\RETURN $z$
\ENDIF
\end{algorithmic}

cref\{l1\}: \cref{l1}, ref\{l1\}: \ref{l1}

\vfill

Test 2

\begin{algorithmic}[1]
\REQUIRE $x$ and $y$
\ENSURE $|x - y|$
\STATE $z = x - y$
\IF{$z<0$}
\RETURN $-z$\label{l2}
\ELSE
\RETURN $z$
\ENDIF
\end{algorithmic}

cref\{l2\}: \cref{l2}, ref\{l2\}: \ref{l2}

\end{document}

• Actually, cleveref 0.18.5 claims to support the algorithms package, which ships the algorithmic package. But you are correct - it is currently not supported, but will be fixed with 0.18.6 (in development). For now only algorithmicx is supported. Commented Aug 6, 2012 at 13:52
• I get ! LaTeX Error: No counter 'ALC@unique' defined. Is the counter name different in algpseudocode package? If it is, how can I find it? Thanks in advance Commented Mar 2, 2022 at 17:23
• @kksagar As far as I can tell the algpseudocode does not need this fix. Make sure you have updated the packages. Commented Mar 3, 2022 at 10:03
• @Karalga The problem seems to persist in the current versions of cleveref Commented Mar 3, 2022 at 10:04
• @Damaru Previously etoolbox was loaded by one of the packages, now (since 2020) \AtBeginEnvironment is part of core LaTeX. Commented Feb 2, 2023 at 19:34