# Why does embedded \g@addto@macro sometimes fail?

I decided to test my understanding of expansion and embed \g@addto@macro within another three macros.

\g@addto@macro
\appendmacro
\layertwo
\activatelayerone


From my understanding, the output in the log for my example below should be:

  ==> item1item2\item \undefinedmacroA item5\undefinedmacroB


But in reality, it is:

  ==> item1item2\item \undefinedmacroA \undefinedmacroB


# Example

\documentclass{article}

\def\macrolist{}

\makeatletter
\def\appendmacro#1{%
}%
\makeatother

\def\activatelayerone#1{%
\def\layertwo##1{%
\appendmacro{##1}
}%
}%

\begin{document}
\null
\appendmacro{item1}
\appendmacro{item2}
\appendmacro{\unexpanded{\item}} % Demonstrate that \unexpanded must be called by the sender
\appendmacro{\unexpanded{\undefinedmacroA}}
\activatelayerone
\layertwo{item5}
\layertwo{\unexpanded{\undefinedmacroB}}
\typeout{ ==> \macrolist}
\end{document}

• unrelated probably but you are missising % from ends of lines again – David Carlisle Jun 16 '16 at 14:26
• \activatelayerone takes an argument ... – Joseph Wright Jun 16 '16 at 14:29
• @JosephWright DOH! Right when I think I am getting it, I make a rookie mistake like that. – Jonathan Komar Jun 16 '16 at 14:30

\def\activatelayerone#1{%

Apart from defining \layertwo to be append and add a spurious space because of the missing %, this acts as \@gobble to discard the next token as #1 is not used. Here the next token is \layertwo so that is discarded and {item5} is just typeset at that point.