94

I've seen sometimes that people use a double pound sign (##) when defining/using arguments.

What is the difference between the normal argument, #1, and the double sign one, ##1? Are there any restrictions for its use? Can you list the good practices, if any, for this type of arguments.

1 Answer 1

98

It allows using arguments in nested macro definitions.

In

\def\a#1{\def\b#1{...}}

the macro \b would not have an argument, since #1 belongs to \a and would be replaced by its argument.

However,

\def\a#1{\def\b##1{...}}

defines \b with an argument. During expansion

  • #1 will be replaced by a parameter
  • ## becomes #

Then \b can use #1 instead of the original ##1.

It follows, that for each level of nesting you need to double the number of # characters:

\def\a#1{\def\b##1{\def\c####1{...}}}

Example:

\documentclass{article}
\def\a#1{\def\b##1{#1 ##1}}
\begin{document}
\a{x} % consequence: \def\b#1{x #1}
\b{y} % prints: x y
\end{document}

In LaTeX syntax this would be:

\newcommand{\a}[1]{%
  \newcommand{\b}[1]{#1 ##1}}

or, as \a and \b are already defined, which you would see if you would try it in the small example,

\renewcommand{\a}[1]{%
  \renewcommand{\b}[1]{#1 ##1}}
5
  • 6
    Why does one need to double each time, i.e. #, ##, #### etc., rather than adding a hash sign for each level, i.e. #, ##, ### etc.?
    – MickG
    Commented Aug 11, 2014 at 13:56
  • 5
    @MickG two possible answers, 1 that's just the way it is or 2 because ## is replaced by # just as #1 is replaced by the first argument, and multiple doubling is just a consequence of that. Commented Aug 11, 2014 at 15:17
  • I just compiled \documentclass{article}\def\a#1{\def\b##1{#1 ##1}}\begin{document}\b{y}\end{document} and I got something like and \underbar{y}: any reason why?
    – pluton
    Commented Mar 16, 2015 at 1:20
  • @pluton you didn't call \a{…} so the built-in \b was used. Try \documentclass{article}\begin{document}\b{y}\end{document} to see that \b{y} has this \underbar{y} behaviour by default. Commented Jul 20, 2017 at 8:23
  • 1
    In other words, nesting 64 deep will create an absolute desaster. I wonder if Saint Knuth has thought about that. Commented Jun 21, 2021 at 10:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .