[Tex/LaTex] Difference between \let\foo\relax and \def\foo{} for disabling

macrostex-core

When I want some macro to (temporarily) do nothing, I normally write

\let\foo\relax

But somebody asked me why I don't just do

\def\foo{}

and I realized I couldn't answer his question.

So, I have two questions:

  1. Can somebody give a practical example of when the two would be different;
  2. For the purpose of disabling a macro, which of the two is preferred?

Here's an example of how I normally use this:

\let\print@style\relax
\def\setprintstyle#1{\def\print@style{#1}}
\def\print#1{\print@style#1}

Best Answer

When you

\def\foo{}

you are giving \foo an empty definition, but \foo still 'exists' using any of the tests used for this (such as \ifdefined or LaTeX's \@ifundefined). The same effect can be achieved by doing

\let\foo\empty

which is very slightly more efficient as it points to an already-used memory location (not a worry nowadays). When \foo has such a definition, it is expandable, and so

\edef\baz{\foo}

will result in \baz being empty, as \foo expands to nothing at all.

On the other hand

\let\foo\relax

makes \foo equal to the \relax primitive. That is a 'do nothing' operation, but importantly is not expandable. So in this case

\edef\baz{\foo}

leaves \baz with definition '\foo'. That can be useful: it's a way of temporarily preventing a macro from doing anything while retaining it's appearance in other code. On the other hand, sometimes you don't want that: it depends on the context. When \foo is equal to \relax, whether it is regarded as 'existing' by the various tests is more variable. TeX automatically creates control sequences equal to \relax in various cases, and so some tests will regard anything equal to \relax as 'not defined'.

So which is better depends on your use case.