# Can I redefine a variable in terms of itself with \def?

So I have a couple variables defined in a TikZ image (specifically an x-value and a y-value of a point), and I'd like to be able to redefine them by adding some value to each. But I'm running into two problems:

1. LaTeX doesn't want to do mathematical operations on variables. So \def \a{1+1} literally sets \a to "1+1" instead of 2.

2. Redefining a variable in terms of itself throws LaTeX into (what I think is) a recursion error. \def \a{\a + 1} leads to the error "TeX capacity exceeded, sorry [input stack size=5000]."

I'd ideally like to do this:

\def \a{0}

% lots of code here

\def \a{\a + 2}

% after this line, I want \a to equal 2, not "0 + 2"


Is there a way to get this result with pgf or something?

• why not go for pgfmathsetmacro Apr 11, 2021 at 2:41
• You cannot \def a macro in terms of itself. You have two options: \edef, if possible. Or else, \let\sva\a and the \def\a in terms of \sva. Apr 11, 2021 at 3:00

You can perform elementary numeric expressions using \numexpr<expr>:

\documentclass{article}

\begin{document}

\def\aaa{0}
\aaa
% lots of code here

\edef\aaa{\number\numexpr\aaa + 2}
\aaa

% after this line, I want \a to equal 2, not "0 + 2"

\end{document}


The above outputs 0 and 2.

Better would be to use xfp; elementary integer calculations are possible via \inteval, otherwise you can use \fpeval:

\documentclass{article}

\usepackage{xfp}

\begin{document}

\def\aaa{0}
\aaa
% lots of code here

\edef\aaa{\inteval{\aaa + 2}}
\aaa

% after this line, I want \a to equal 2, not "0 + 2"

\end{document}

• Thank you! I tried xfp and it works like a charm. Apr 12, 2021 at 3:02