How to dynamically refer to nodes within tikz environment? [duplicate]

Here is my code with two tikzpictures. I was expecting both to produce similar output.

\documentclass{article}
\usepackage{tikz}
\begin{document}

\begin{tikzpicture}
\node[rectangle,draw,minimum size=5mm] (r0) at (0, 0) {};
\node[rectangle,draw,minimum size=5mm] (r1) at (10mm, 0) {};
\node[rectangle,draw,minimum size=5mm] (r2) at (20mm, 0) {};
\node[rectangle,draw,minimum size=5mm] (r3) at (30mm, 0) {};
\draw[->] (r0) -- (r1);
\draw[->] (r1) -- (r2);
\draw[->] (r2) -- (r3);
\end{tikzpicture}

\vspace{20mm}

\begin{tikzpicture}
\foreach \i in {0,...,3}
\node[rectangle,draw,minimum size=5mm] (r\i) at (10mm * \i, 0) {};
\foreach \i in {0,...,2} {
\pgfmathsetmacro{\j}{\i + 1}
\draw[->] (r\i) -- (r\j);
}
\end{tikzpicture}

\end{document}


Here is the output.

Why are the arrows in the second tikzpicture environment piercing into the boxes? What makes the code in the second tikzpicture environment different from the first one?

• You need \pgfmathtruncatemacro{\j}{\i + 1} and this question is a duplicate, I only need to find it. Nov 29 '17 at 3:59
• Don't you get an error?
– cfr
Nov 29 '17 at 4:02
• @cfr The only suspicious thing I get in the output while running pdflatex is ABD: EveryShipout initializing macros. Don't know if this is trying to tell me that there has been an error. Nov 29 '17 at 4:04
• @LoneLearner That is just a message from the everyshi package which is loaded by TikZ to be able to draw on the page background. Nothing to be worried about. Nov 29 '17 at 4:12
• Never mind me. You won't get an error because the decimal part of the values will be treated as a node anchor very close to 0 i.e. east.
– cfr
Nov 29 '17 at 18:17