[Tex/LaTex] Expand macro in Latex

calculations

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.

Best Answer

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.

Related Question