What's wrong with this macro definition `\newcommand{\funk}[2]{#1}{-#2}`?

What's wrong with this macro definition `\newcommand{\funk}[2]{#1}{-#2}`?

Here is a MnWE:

\documentclass{minimal}
\usepackage{amsmath}

\newcommand{\funk}[2]{#1}{-#2}

\begin{document}
    $\funk{x}{2}$
\end{document}

It does not compile, giving me the error message:

You can't use `macro parameter character #' in horizontal mode. \newcommand{\funk}[2]{#1}{-#

What's wrong with the command?

답변1

The formal specification for \newcommand is

\newcommand*{<cmd>}[<args>][<default>]{<stuff>}

where * is optional (implies whether the resulting \definition will be \long or not), <cmd> is a non-existent control sequence, <args> (also optional) denote the number of arguments passed gobbled by <cmd>, <default> is the default value of an optional argument if it is not specified (when <args> > 0) and <stuff> is the expansion (or replacement text) of <cmd> after gobbling the arguments. Each argument (up to 9) is replaced by #<num> for the <num>th argument (#1 for the first, #2 for the second, and so forth).

In your setup

\newcommand{\funk}[2]{#1}{-#2}

\funk takes 2 arguments, both mandatory and the replacement text is just the first argument #1 (effectively gobbling the second).

{-#2} does not form part of the control sequence creation, and therefore is expanded as-is, leaving -#2 in the input stream (in the preamble), which is not allowed as # has special meaning - it's a macro parameter character.

You're probably interested in

\newcommand{\funk}[2]{#1-#2}

관련 정보