7

I have seen the following definition in a class file (which we use internally):

\newcommand{\@TitleBackground}{default}
\newcommand{\titlebackground}{\renewcommand{\@TitleBackground}}

This provides \titlebackground as a command for changing \@TitleBackground, but how/why does it work? I would understand it if the second line was

\newcommand{\titlebackground}[1]{\renewcommand{\@TitleBackground}{#1}}

but why does it work also without the argument, i.e, with \renewcommand having onle one parameter?

And does the shorter version has some advantages or disadvantages over the longer one?

  • 2
    Because when you do \titlebackground{something}, TeX expands \titlebackground to \renewcommand{\@TitleBackground} and you have \renewcommand{\@TitleBackground}{something}, which is slightly faster than grabbing the argument once, and passing it again to \renewcommand (which is not wrong either). – Phelype Oleinik Oct 23 at 12:03
  • 2
    Although the macro you're asking about is different, the principle is the same as explained here: tex.stackexchange.com/q/509471/134574. – Phelype Oleinik Oct 23 at 12:08
7

With \newcommand{\titlebackground}{\renewcommand{\@TitleBackground}}, the following happens when \titlebackground{whatever} is processed: \titlebackground is replaced by its expansion, so TeX will restart from

\renewcommand{\@TitleBackground}{whatever}

and eventually do \def\@TitleBackground.

With \newcommand{\titlebackground}[1]{\renewcommand{\@TitleBackground}{#1}}, upon finding \titlebackground{whatever} TeX will start expanding \titlebackground; since now this is a macro with an argument, TeX absorbs it and replaces the whole \titlebackground{whatever} with the replacement text, getting at

\renewcommand{\@TitleBackground}{whatever}

as before. So the difference is that in the second case {whatever} is looked at as an argument one more time than in the first version.

The difference is negligible. On my machine, doing a job like in the second case one million times require 1/100 of a second longer than the first way.

  • So, they will get exactly the same result, will basically the same speed - but the shorter one hides the fact that the command needs an argument - not only from humans, but also from editors like TeXstudio that actually parse \newcommand .. correct? – Michal Kaut Oct 24 at 13:18
  • @MichalKaut Yes, the second way is clearer under several aspects, clarity is usually preferable to efficiency at all costs. – egreg Oct 24 at 13:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.