# pgfmathsetmacro issue in foreach

I am trying to use \pgfmathsetmacro inside a foreach loop to connect nodes which are adjacent and named according to position as follows:

\foreach \src in {0,...,\T}{
\pgfmathsetmacro{\dest}{\src+1};
\path (n-\src-1) edge[<-] (n-\dest-1);
};


This however leads to the following error during compilation:

./nn.tex:54: Package pgf Error: No shape named n-1 is known. [    }]
./nn.tex:54: Package pgf Error: No shape named n-2 is known. [    }]
./nn.tex:54: Package pgf Error: No shape named n-3 is known. [    }]
./nn.tex:54: Package pgf Error: No shape named n-4 is known. [    }]


which makes it seem as though the \dest value is not available. How do I get around this issue?

After the definition via \pgfmathsetmacro, the macro \dest contains a real number (1.0, 2.0, ...), but very likely you need an integer. This can be achieved by using \pgfmathtruncatemacro instead of \pgfmathsetmacro to cut the decimal fraction part:

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\path
\foreach \src in {0, ..., 4} {
(\src, 0) node[circle, draw] (n-\src-1) {}
}
;

\foreach \src in {0, ..., 3} {
\pgfmathtruncatemacro{\dest}{\src+1};
\path (n-\src-1) edge[<-] (n-\dest-1);
};
\end{tikzpicture}
\end{document}


Alternatively an integer addition can be used, e.g. via eTeX's \numexpr:

\edef\dest{\the\numexpr(\src)+1}


Another method uses the evaluate key (instead of \pgfmathsetmacro) and the int function (to truncate your addition):

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\path
\foreach \src in {0, ..., 4} {
(\src, 0) node[circle, draw] (n-\src-1) {}
}
;

\foreach \src [evaluate=\src as \dest using int(\src + 1)]
in {0, ..., 3} {
\path (n-\src-1) edge[<-] (n-\dest-1);
};
\end{tikzpicture}
\end{document}


• Another possibility would be to run over \dest and use the remember method of TikZ's \foreach, as in \foreach \dest [remember=\dest as \src (initially 0)] in {1,...,4} {…}. – Henri Menke Dec 6 '15 at 11:31