0

The answer 969/29410 showed that it is possible to use optional arguments in environment definitions:

\documentclass{article}
\newenvironment{hello}[1][world]{\noindent Hello #1, }{Bye now!\\}
\begin{document}
\begin{hello}[Bob]\end{hello}
\end{document}

This works fine and produces

Hello Bob, Bye now!

Why is it that the optional argument cannot be used in the closing statement?

\documentclass{article}
\newenvironment{hello}[1][world]{\noindent Hello, }{Bye now, #1!\\}
\begin{document}
\begin{hello}[Bob]\end{hello}
\end{document}

line 2: Illegal parameter number in definition of \endhello. ...][world]{\noindent Hello, }{Bye now, #1!\}

line 4: You can't use `macro parameter character #' in horizontal mode. \begin{hello}[Bob]\end{hello}

line 4: Underfull \hbox (badness 10000) in paragraph

  • 4
    You can't use arguments in the \end{part} of the environment. See this. You can, however, do \def\MyEnvOptArg{#1} in the \begin part and use \MyEnvOptArg instead of #1 in the \end part. – Phelype Oleinik Feb 12 at 11:37
  • Or use xparse or environ – TeXnician Feb 12 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.