In “algorithmic” environment, how can I place a comment before a statement

algorithmic

In the algorithmic environment, I can use the \Comment macro to put a comment after a statement. But when I try to put it before the first statement in an algorithm, I get an error. Is there a way to put a comment before a statement? e.g.:

// The following line initializes the variable x.

Let x = 0

Best Answer

Comments in pseudocode are typically set on the right, but you can use \Statex to set a blank (unnumbered) \State and then insert whatever you like as a comment:

enter image description here

\documentclass{article}

\usepackage{algorithm,algpseudocode}

\begin{document}

\begin{algorithm}
  \caption{Euclid's algorithm}
  \begin{algorithmic}[1]
    \Function{Euclid}{\null}\Comment{The gcd of $a$ and $b$}
      \Statex \textit{// The following line initializes the variable $r$}
      \State $r \gets a \bmod b$
      \While{$r \neq 0$}\Comment{We have the answer if $r$ is 0}
        \State $a \gets b$
        \State $b \gets r$
        \State $r \gets a \bmod b$
      \EndWhile
      \State \textbf{return} $b$\Comment{The gcd is $b$}
    \EndFunction
  \end{algorithmic}
\end{algorithm}

\end{document}