# Comment on the same line as \If in algorithm introduces a vertical whitespace

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:

Anyone knows how to fix that?

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}


• As an addendum: if you wish your comment to show up at the right edge of the algorithm, rather than right next to the text, use [f] instead (as also explained on the same page) Dec 2, 2018 at 13:32