8

See the examples below:

\documentclass{article}

\begin{document}
\def\a{1}
\def\b{\def\a{2}}
\def\c{\b}
\c\a
\end{document}

In expansion stage, \def, its parameter text and replacement text is not expanded. Then how can TeX processor know \c, \a is a macro in this stage?

And the tokens are expanded one by one, so I have

\c\a ==>
\b 1 ==>
\def\a{2} 1

but the output is 2. It is the correct and normal output if I don't think about this things, but apparently I have misunderstanded something about the expansion stage and execution stage.

2 Answers 2

11

When TeX is expanding tokens and finds a macro, it replaces it with the macro’s replacement text, after having absorbed the arguments, if so specified by the macro. Then it restarts from the first token in the replacement text.

Thus the steps with your code are

\c\a
\b\a
\def\a{2}\a
     <do the assignment>
\a
2

To complement the above description, when TeX finds it has to perform an assignment (here \def), it absorbs the needed tokens, stores the assignment in memory and removes those tokens from the input stream.

Thus \a is not examined until it is the first token in the input stream, unless the order of expansion is modified with \expandafter.

You’d get 1 with

\expandafter\c\a

A further call to \a, would deliver 2.

6

Expansion is depth first, that is, \c will be completely expanded before \a is expanded, so it will go like this:

\c\a ==>
\b\a ==>
\def\a{2}\a ==>
2

You must log in to answer this question.

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