7

I have a pretty simple problem but have been unable to look for a simple answer. It's about macro expansion.

Let's say I define 4 symbols:

\documentclass{minimal}

\newcommand* \A {1}
\newcommand* \B {2}
\newcommand* \C {\A + \B}
\newcommand* \D {\C + 1}

\begin{document}
A = \A, B = \B, C = \C, D = \D
\end{document}

The print out is A = 1, B = 2, C = 1+ 2, D = 1+ 2+ 1. Is there are way to expand the macros so that A = 1, B = 2, C = 3, D = 4? I know there is the \expandafter macro but its syntax is brutal. I would like to remain within the simplicity of Latex if possible.

Joseph Wright
  • 259,911
  • 34
  • 706
  • 1,036
  • Welcome to TeX.SX! TeX is a typesetting language, so it doesn't perform computations when you don't explicitly tell it to: one wants to typeset $2+2=4$, after all. – egreg Nov 04 '13 at 15:29
  • You can do this with basic TeX or a package such as calc. –  Nov 04 '13 at 15:35

1 Answers1

15

You don't want to “expand” macros, but rather to do computations. Expansion is the process by which a macro is replaced by its “replacement text”. So, when TeX finds \A it replaces it with 1; however TeX will never do computations unless precisely instructed to do so, because it's a language aimed at typesetting and somebody would want to print

2 + 2 = 4

and this shouldn't be replaced by 4=4 under the hood.

You can easily define a \compute macro for doing with integers.

\documentclass{article}

\newcommand* \A {1}
\newcommand* \B {2}
\newcommand* \C {\A + \B}
\newcommand* \D {\C + 1}

\newcommand{\compute}[1]{\number\numexpr#1\relax}

\begin{document}
$A = \compute{\A}$, $B = \compute{\B}$, 
$C = \compute{\C}$, $D = \compute{\D}$
\end{document}

enter image description here

Of course, \compute{\A} isn't really necessary, since \A expands directly to 1.

egreg
  • 1,121,712