[Tex/LaTex] What are the differences between \def, \edef, \gdef and \xdef?

tex-core

I am a LaTeX guy, slowly working into the miracles of TeX.

Can anybody tell me the differences between \def, \edef, \gdef and \xdef?

Where shall I use which, what are the pros and cons? Or is it suspected to be unclean code, if I mix TeX commands in LaTeX?

Please give a short example, of how to use the command.

Best Answer

There are no pros and cons: \def and \edef perform different tasks. With

\def<cs><parameter text>{<replacement text>}

you define <cs> to look for its arguments (if any) and to be replaced by <replacement text>, which is not interpreted in any way at definition time. With

\edef<cs><parameter text>{<replacement text>}

the replacement text is fully expanded at definition time.

For instance, if we have

\def\aaa{aaa}
\def\bbb{x\aaa}
\edef\ccc{y\aaa}
\def\aaa{AAA}

a call like

\bbb \ccc

would produce

xAAAyaaa

because the replacement text of \ccc is what remains after full expansion, so \edef\ccc{y\aaa} is the same as \def\ccc{yaaa}.

Note that the expansion in \edef is done at definition time, so parameter tokens like #1 and so on will be untouched.

A less silly example: if you want that \thissection expands to the value of the section counter at the time the command is defined, you have to say

\edef\thissection{\thesection}

because this “freezes” the value by doing the expansion at definition time. To the contrary, with \def\thissection{\thesection} the macro \thissection would print the current section number.

LaTeX has the variant \protected@edef that avoids some quirks with “robust macros”, so something like \protected@edef\cs{\textbf{a}} works whereas \edef\cs{\textbf{a}} wouldn't (there's plenty of examples on the site).

About \gdef and \xdef there's not much to say: the former is completely equivalent to \global\def and the latter to \global\edef (assuming primitive meaning of \global, of course). LaTeX has \protected@xdef.