# Using counters within \index{…}

When trying to use a counter value within \index an odd behavior occurs. It seem as if the value would be evaluated at the end of the document, when the counter has already been changed. Therefore all the occurrences of the counter have the same value.

\documentclass{article}

\usepackage{makeidx}
\makeindex

\begin{document}

\section{First Section}
\index{first \arabic{section}}

\section{Second Section}
\index{second \arabic{section}}

\section{Third Section}
\index{third \arabic{section}}

\printindex

\end{document}


results in the following index:

though I would like to have:

-

\index reads its argument verbatim like, thus macros do not get expanded. Thus you will see \arabic{section} in the generated index file and the number of counter section at the time, when the index is set.

One method is to use a macro \Index that reads its argument before passing to the verbatim reading \index. This way the macros gets expanded. Unwanted expansion can be turned off by using \string in front of the macro.

\documentclass{article}

\usepackage{makeidx}
\makeindex

\newcommand*{\Index}[1]{\index{#1}}

\begin{document}

\section{First Section}
\Index{first \arabic{section}}

\section{Second Section}
\Index{second \arabic{section}}

\section{Third Section}
\Index{third \arabic{section}}

\printindex

\end{document}


Results:

• test.idx:
\indexentry{first 1}{1}
\indexentry{second 2}{1}
\indexentry{third 3}{1}

• test.ind:
\begin{theindex}

\item first 1, 1

\indexspace

\item second 2, 1

\indexspace

\item third 3, 1

\end{theindex}

• Index:

-

The argument of \index is read verbatim as that;s normally what is required. You don't want that, so the easiest thing is to put \index inside any command. \mbox would do:

\documentclass{article}

\usepackage{makeidx}
\makeindex

\begin{document}

\section{First Section}

\mbox{\index{first \arabic{section}}}

\section{Second Section}
\mbox{\index{second \arabic{section}}}

\section{Third Section}
\mbox{\index{third \arabic{section}}}

\printindex

\end{document}

-

Another alternative is to use \label/\ref pairs

\documentclass{article}

\usepackage{makeidx}
\makeindex

\begin{document}

\section{First Section}\label{sec:one}
\index{first \ref{sec:one}}

\section{Second Section}\label{sec:two}
\index{second \ref{sec:two}}

\section{Third Section}\label{sec:three}
\index{third \ref{sec:three}}

\printindex

\end{document}

-
The problem is sorting, makeindex sees \ref{...} and sorts the entries according to the label name instead of the actual text of the reference. \index{...@...} does not help either, because the expanded reference is needed before \index reads its argument in verbatim manner. –  Heiko Oberdiek Nov 17 '12 at 20:10