[Tex/LaTex] \begingroup, \endgroup expansion problem “Undefined control sequence.”

errorsexpansion

I just created an answer that uses a temporary variable with \write\@auxout and thought it would be good idea to scope with \begingroup, \endgroup. For some Reason this results in:

! Undefined control sequence.
<write> \tempvariable

MWE

\documentclass{article}

\makeatletter
\newcommand{\abc}{%
    \begingroup%
    \newcommand\tempvariable{\relax}%
    \write\@auxout{\tempvariable}%
    \endgroup%
}
\makeatother

\begin{document}
    Why isn't this working???
    \abc 

\end{document}

Why is this happening and how can I fix this?

Best Answer

Adding \immediate should help:

\documentclass{article}

\makeatletter
\newcommand{\abc}{%
   \begingroup%
    \newcommand\tempvariable{\relax}%
%    \write\@auxout{\tempvariable}%
\immediate \write\@auxout{\tempvariable}%
    \endgroup%
}
\makeatother

\begin{document}
    Why isn't this working???
    \abc 

\end{document}

I can see from your anwer from the link, that you know command \immediate, so probably no additional comment is needed.