[Tex/LaTex] comment in algorithmic on a line beginning with if

algorithmic

I'm working with algorithmic to create some pseudo-code with comments. With a macro found on this site (see header), comments will be aligned on the right, which is wonderful.

However, I don't get it how to have a comment on a line beginning with \IF.

Below is a SSCCE, that shows a workaround.

\documentclass{report}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{array}
\usepackage{eqparbox}
\renewcommand\algorithmiccomment[1]{%
  \hfill\#\ \eqparbox{COMMENT}{#1}%
}

\begin{document}
  \begin{algorithm}[h]
    \begin{algorithmic}[1]
      \STATE $math$ \COMMENT{comment 1}
      \IF{$moremath$}
        \STATE \COMMENT{comment 2 one line up please}
        \STATE $lastmath$
      \ENDIF
    \end{algorithmic}
  \end{algorithm}
\end{document}

This modification does not work, pdflatex chokes up on \STATE $lastmath$.

  \begin{algorithm}[h]
    \begin{algorithmic}[1]
      \STATE $math$ \COMMENT{comment 1}
      \IF{$moremath$} \COMMENT{comment 2 on line 2 please} %\STATE removed, won't work!
        \STATE $lastmath$
      \ENDIF
    \end{algorithmic}
  \end{algorithm}

I use pdflatex. How can I modify my code to have the comments in line 1 and 2, rather than having comment 2 on a separate line (workaround)?

Best Answer

Comments on if statements are to be provided as on optional argument to \IF rather than via the \COMMENT command. See section 3.12 of the documentation, this also applies to \ELSIF, \ELSE, \WHILE, \FOR, \FORALL, \REPEAT and \LOOP.

Sample output

\documentclass{report}

\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage{array}
\usepackage{eqparbox}
\renewcommand\algorithmiccomment[1]{%
  \hfill\#\ \eqparbox{COMMENT}{#1}%
}

\usepackage{etoolbox}  % patch def of algorithmic environment
\makeatletter
\patchcmd{\algorithmic}{\addtolength{\ALC@tlm}{\leftmargin} }{\addtolength{\ALC@tlm}{\leftmargin}}{}{}
\makeatother

\begin{document}
\tracingmacros=1
  \begin{algorithm}[h]
    \begin{algorithmic}[1]
      \STATE {$math$} \COMMENT{comment 1}
      \IF[comment 2 on line 2]{$moremath$}
        \STATE $lastmath$ \COMMENT{comm 3}
      \ENDIF
    \end{algorithmic}
  \end{algorithm}
\end{document}

Update a spurious space in the definition of the ALC@g environment inside the algorthmic environment cased misalignemnt of the comments. Patch added above to code.