[Tex/LaTex] How to fix Illegal parameter number in definition of a new Tikz command

macrostikz-pgf

This small piece of code isn't working.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shapes.multipart}
%
\newcommand{\Stack}{
\begin{tikzpicture}[stack/.style={rectangle split, rectangle split parts=#1,draw, anchor=center}]
\node[stack=3]  {
\nodepart{one}\texttt{int} 1
\nodepart{two}\texttt{int} 2
\nodepart{three}\texttt{int} 3
};
\end{tikzpicture}
}
\begin{document}
\Stack
\end{document}

It gives the following error:

Illegal parameter number in definition of \Stack.

1
l.18 }

The code is tested and works fine otherwise. Can someone help please?

Best Answer

The problem here is that when you have #1 in a \newcommand definition, that is interpreted as being an argument for the macro itself, and you need to specify how many arguments your macro should take. For example if you define

\newcommand\foo{#1}

that will throw the same error. The correct definition would be

\newcommand\foo[1]{#1}

Where the [1] states that this macro takes one mandatory argument, the default being zero I think, and you would call the macro as

\foo{bar}

When you have a style with an argument, that is (probably) akin to having a second macro definition inside the definition of \Stack. So to make the #1 belong to the style, you need to use ##1 instead, as daleif mentioned. The double # indicates that the argument is for the "inner" macro. See What is the meaning of double pound symbol (number sign, hash character) ##1 in an argument? for more discussion about that.

But in your case you seem to always have the same argument for that style (3), so it would perhaps make more sense to modify the style definition to have rectangle split parts=3 instead of rectangle split parts=#1, and change stack=3 to stack in the node.