TikZ-PGF – Coordinate Calculations

macrostikz-pgf

I have very simple problem, and I also have a solution to the problem. But I am hoping for a better solution:) Consider the following code:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
  \begin{tikzpicture}
    \foreach \x in {1,2,3} {
      \coordinate (V\x) at ($(\x-1,0)$);
    }
    \foreach \x in {1,2} {          
      \draw[black] ($(V\x)$) -- ($(V{\x+1})$);
    }
  \end{tikzpicture}
\end{document}

In the first \foreach loop the calculation \x+1 works fine, however in the second loop the problem is that $(V{\x+1})$ expands to V{1+1} and not V2.. I hope there is way to avoid defining another variable to solve this..
I know I could solve this writing

\foreach \x in {1,2} {
   \pgfmathtruncatemacro{\y}{\x+1};
   \draw[black] ($(V\x)$) -- ($(V\y)$);
 }

But this feels like overkill to me :).. Is there a way to avoid using \pgfmathtruncatemacro here?

Best Answer

The following should do the trick. You can compute values and assign them to macros.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
  \begin{tikzpicture}
    \foreach \x in {1,2,3} {
      \coordinate (V\x) at ($(\x-1,0)$);
    }
    \foreach \x [evaluate=\x as \sx using int(\x+1)] in {1,2} {
      \draw[black]
           ($(V\x)$) -- ($(V\sx)$);
    }
  \end{tikzpicture}
\end{document}