[Tex/LaTex] Comment on the same line as \If in algorithm introduces a vertical whitespace

algorithm2ealgorithmscomments

I am using the algorithm2e package to write a pseudo code algorithm. I would like to add a comment with \tcp, on the same line as an \If statement. I managed to do so by putting the \tcp command between parenthesis right after the \If, but it introduces a vertical space between the If and the following line.

\usepackage[titlenumbered,ruled,noend,algo2e]{algorithm2e}
\usepackage{algorithm}

\begin{document}
    \begin{algorithm}[t]
        \If(\tcp*[l]{comment}){$k = K$}{do stuff}
        \If{$k \neq K$}{do other stuff}
    \end{algorithm}
\end{document}

Results in:

enter image description here

Anyone knows how to fix that?

Best Answer

You should use the [h] specification of \tcp*, as explained here at page 32.

\documentclass{article}
\usepackage[titlenumbered,ruled,noend,algo2e]{algorithm2e}
\usepackage{algorithm}

\begin{document}
    \begin{algorithm}[t]
        \If(\tcp*[h]{comment}){$k = K$}{do stuff}
        \If{$k \neq K$}{do other stuff}
    \end{algorithm}
\end{document}

enter image description here

Related Question