# Order of statements in foreach loops

When I deal with more then one statement in foreach loops, it seems that LaTeX deals differently with the order of the statements than I thougt.

MWE:

\documentclass{article}
\usepackage{pgffor}
\begin{document}
\pgfmathtruncatemacro{\b}{1}
\foreach \i in {1,2} {
\pgfmathtruncatemacro{\a}{\b+1}
\pgfmathtruncatemacro{\b}{\a}
\a
}
\end{document}


The output should be 2 3 but it is 2 2. How can this be done?

• The changes within a \foreach loop are local and get lost at the end. So \b has always value 1 at the beginning of each iteration. – gernot Apr 10 '17 at 9:04
• can the canges somehow be done global? – Martin Apr 10 '17 at 9:05
• Use {\b+\i} instaed of {\b+1} – ferahfeza Apr 10 '17 at 9:06

The changes within a \foreach loop are local and get lost at the end. So \b has value 1 at the beginning of each iteration.

The tikz way around it is to use the remember key.

\documentclass{article}
\usepackage{pgffor}
\begin{document}
\pgfmathtruncatemacro{\b}{1}
\foreach \i [remember=\b as \b] in {1,2} {
\pgfmathtruncatemacro{\a}{\b+1}
\pgfmathtruncatemacro{\b}{\a}
\a
}
\end{document}


Using all options of the remember key you can write your code more succinctly as

\documentclass{article}
\usepackage{pgffor}
\begin{document}
\foreach \i [remember=\a as \b (initially 1)] in {1,2} {
\pgfmathtruncatemacro{\a}{\b+1}
\a
}
\end{document}


For the details see the tikz manual.

You can bypass tikz and make global assignments. Note that \b is already in use, so redefining it globally may have unintended side effects.

\documentclass{article}
\usepackage{pgffor}
\begin{document}
\renewcommand\b{1}
\foreach \i in {1,2} {
\pgfmathtruncatemacro{\a}{\b+1}
\xdef\b{\a}
\a
}
\end{document}