[Tex/LaTex] Faulty right alignment for comments in algorithmic package

algorithmiccommentshorizontal alignmentpseudocode

I'm trying to right align comments in a pseudocode environment using the algorithmic package. So I renewed the algorithmiccomment command.

There's a different way to create comments for "normal" statements and for pre-defined statements such as "for", "if", etc.

The problem is, that the right alignment differs for the "normal" comments and the others. How can that be fixed, so that all comments nicely align?

Here's what I mean.

Comments not really aligned well

And this is the code to reproduce my example. Any help is greatly appreciated.

\documentclass[a4paper]{article}
\usepackage{algorithmic}
\renewcommand{\algorithmiccomment}[1]{\hfill \tiny//~#1\normalsize}

\begin{document}
\begin{algorithmic}
\FORALL[This comment is not quite right aligned]{ $a \in B$}
    \STATE X  \COMMENT{This comment is further to the right}
\ENDFOR
\end{algorithmic}
\end{document}

Best Answer

If you don't mind to switch to the algorithmicx package (algpseudocode variant) the issue is solved.

Note that I've loaded it with the compatible option so you can use your old algorithms without any change.

\documentclass[a4paper]{article}
\usepackage[compatible]{algpseudocode} % or \usepackage{algcompatible}
\renewcommand{\algorithmiccomment}[1]{\bgroup\hfill\tiny//~#1\egroup}

\begin{document}
\begin{algorithmic}
\FORALL[This comment is not quite right aligned]{ $a \in B$}
    \STATE X  \COMMENT{This comment is further to the right}
\ENDFOR
\end{algorithmic}
\end{document} 

Output

enter image description here

And this is how it should be written in "proper" algorithmicx syntax:

\documentclass[a4paper]{article}
\usepackage{algpseudocode}
\renewcommand{\algorithmiccomment}[1]{\bgroup\hfill\tiny//~#1\egroup}

\begin{document}
\begin{algorithmic}
\ForAll{ $a \in B$} \Comment{This comment is not quite right aligned}
    \State X \Comment{This comment is further to the right}
\EndFor
\end{algorithmic}
\end{document}
Related Question