[Tex/LaTex] Why SetKwData defined macro for algorithm2e doesn’t work in caption

algorithm2ecaptionsmacros

I defined a macro with \SetKwData command from algorithm2e but it doesn't seem to be working in the caption.

My code:

\documentclass[10pt,a4paper,twoside]{report}

\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\DontPrintSemicolon
\SetKwData{Result}{result}

\begin{document}
\begin{algorithm}
  \KwIn{ \(x\) and \(y\)  }
  \KwOut{ \Result }
  \( \Result \leftarrow x + y \) \;
  \Return{ \Result  }
  \caption{ This is a caption with \Result. }
\end{algorithm}
In here I talk about the \Result of \(x + y \).

\end{document}

The error:

! Argument of \@caption has an extra }.
<inserted text> 
                \par 
l.72   \caption{ This is a caption with \Result. }

Best Answer

You need to \protect the \result or use the optional short caption.

\documentclass[10pt,a4paper,twoside]{report}

\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\DontPrintSemicolon
\SetKwData{Result}{result}

\begin{document}
\begin{algorithm}
  \KwIn{ \(x\) and \(y\)  }
  \KwOut{ \Result }
  \( \Result \leftarrow x + y \) \;
  \Return{ \Result  }
  \caption{ This is a caption with \protect\Result. }
\end{algorithm}
In here I talk about the \Result of \(x + y \).

\end{document}

Side note

Apart from the missing \protect, your input has several wrong spaces. Recall that spaces are ignored in math mode, but not in all cases when TeX is typesetting text. So you should be more careful: \Return{ \Result } is not the same as \Return{\Result}.

\documentclass[10pt,a4paper,twoside]{report}

\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\DontPrintSemicolon
\SetKwData{Result}{result}

\begin{document}
\begin{algorithm}
  \KwIn{\(x\) and \(y\)}
  \KwOut{\Result}
  \( \Result \leftarrow x + y \) \;
  \Return{\Result}
  \caption{This is a caption with \protect\Result.}
\end{algorithm}
In here I talk about the \Result of \(x + y \).

\end{document}
Related Question