Why does my calculated node reference behave differently?

Here's a MWE to show what I mean:

\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \x in {0, ..., 4}
\node[circle,draw] (n\x) at ({2*\x}, 0) {\x};
\foreach \x in {0, ..., 3} {
\pgfmathsetmacro{\y}{\x+1}
\draw[red] (n\x) to[bend left] (n\y);
\draw[blue] (n\x) circle (.2);
\draw[gray,fill] (n\y) circle (.05);
}
\end{tikzpicture}
\end{document}


I would expect this to create a few circular nodes, named n0 through n4, and connect subsequent pairs by lines going from edge to edge. However, while the (n\x) reference correctly refers to the node at \x, (n\y) in all instances somehow collapses to a single point, which is not even in the center:

Why does \y behave differently that \x?

I know how to make this work, for example using /pgf/foreach/remember, but I'm curious.

• If you print out the value of \y you'll see that it's a real number (1.0, 2.0, etc.). – Sergei Golovan Oct 13 '20 at 14:32
• Interesting!! So the .0 chooses a particular point, like .west? – The Vee Oct 13 '20 at 14:35
• Looks like it. \pgfmathtruncatemacro truncates the decimal part. – Sergei Golovan Oct 13 '20 at 14:40

When x = 0, \pgfmathsetmacro{\y}{\x+1} defines \y to 1.0. Then node n1.0 means a point at the boundary of node n1 and at angle 0.

To get \y defined to 1, here you can use one of the following (the last two are both suggested by @Alenanno from this comment),

• pgfmath function int: \pgfmathsetmacro{\y}{int(\x+1)},
• pgfmath macro \pgfmathtruncatemacro: \pgfmathtruncatemacro{\y}{\x+1}, and
• pgffor option evaluate accompanied by int function: \foreach \x [evaluate=\x as \y using int(\x+1)] in {0, ..., 3} {...}.
\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \x in {0, ..., 4}
\node[circle,draw] (n\x) at ({2*\x}, 0) {\x};
\foreach \x in {0, ..., 3} {
\pgfmathsetmacro{\y}{int(\x+1)}
\draw[red] (n\x) to[bend left] (n\y);
\draw[blue] (n\x) circle (.2);
\draw[gray,fill] (n\y) circle (.05);
}
\end{tikzpicture}
\end{document}


• I never knew about the angle, this is super useful! – The Vee Oct 13 '20 at 14:43
• @TheVee You can also use \pgfmathtruncatemacro\y{\x+1}. :) And since it's a foreach, you can directly do \foreach \x [evaluate=\x as \y using int(\x+1)] in {0, ..., 3} {% ... – Alenanno Oct 13 '20 at 15:50
• @Alenanno I've added your suggestions to my answer, and thanks! – muzimuzhi Z Oct 13 '20 at 16:57