# Updating a variable

I define a variable using \def\x{0}. How can I update this variable by adding 1?

\def\x{\x+1} doesnt work (it just gets stuck in an infinite loop)

Or can I define variables in some other way that can do this?

• Welcome to TeX.sx! Usually, we don't put a greeting or a "thank you" in our posts. While this might seem strange at first, it is not a sign of lack of politeness, but rather part of our trying to keep everything very concise. Accepting and upvoting answers is the preferred way here to say "thank you" to users who helped you. – jub0bs Mar 29 '13 at 16:10
• If you only want to manipulate integers, you can use \newcounter{x} \addtocounter{x}{1}. You can access the value via \value{x}; in particular, \the\value{xx} print the value of counter x. – jub0bs Mar 29 '13 at 16:17
• @Jubobs You have a wrong \the\value{xx} that should be \the\value{x} (or the simpler \arabic{x}). – egreg Mar 29 '13 at 16:31
• Oops. You're right. – jub0bs Mar 29 '13 at 16:36
• @egreg: Or another simpler one (compared to \arabic{x}): \thex. – kiss my armpit Mar 29 '13 at 23:28

It's better to manage integer variables with TeX's registers. You can say

\newcount\x


and then use it in all contexts a number is required. Advancing a counter is done by

\advance\x by 1


or any other integer. In order to print the value of this counter you have to say \number\x.

However, it depends on what you want to do with those "variables". A different approach might be

\def\newvariable#1{\gdef#1{0}}


so that

\newvariable\x


will define \x to expand to 0; with

\incrvariable\x


it would expand to 1; with a following

\addtovariable\x{41}


it would expand to 42. Not that I recommend such a way to go.

Without PSTricks.

\documentclass[preview,border=12pt,varwidth]{standalone}
\usepackage[nomessages]{fp}
% #1: (optional) the number of digits after decimal point, the default is zero to make an integer
% #2: (mandatory) the name of variable to create
% #3: (mandatory) mathematics expression in infix form
\newcommand\const[3][0]{%
\edef\temporary{round(#3}%
\expandafter\FPeval\csname#2\expandafter\endcsname
\expandafter{\temporary:#1)}%
}

\const{x}{10}
\const{y}{x^2}

\begin{document}
\x% print 10

\x% print 30

\y% print 100, not 900!
\end{document}


## Application (finding the fixed point of cos(x))

\documentclass[preview,border=12pt,varwidth]{standalone}
\usepackage[nomessages]{fp}
% #1: (optional) the number of digits after decimal point, the default is zero to make an integer
% #2: (mandatory) the name of variable to create
% #3: (mandatory) mathematics expression in infix form
\newcommand\const[3][0]{%
\edef\temporary{round(#3}%
\expandafter\FPeval\csname#2\expandafter\endcsname
\expandafter{\temporary:#1)}\ignorespaces
}

\def\f(#1){cos(#1)}

\const[5]{x}{0}

\begin{document}
\newcount\i
\i=1
\loop
\unless\ifnum\i>35