# What is the correct way to use the foreach command in a Tikz loop?

I am trying to define nodes in a path. I have come up with the following TikZ code which fails to compile:

\begin{tikzpicture}
[
hlc/.style={circle,inner sep=5,draw}
]
\def\odl{0,...,7};
\path foreach \x in \odl { node[hlc] (\x) at (\x,\x) {\x}; }
\end{tikzpicture}


Could some one point out to me what is wrong with my code. Thanks in advance.

Every spin of the loop should produce a valid path specification. But because you have the semicolon inside the loop, after first spin, it is basically trying to make sense what \x might be and thinks that you are trying to execute some non-TikZ code and trips. Effectively it is trying to do this

\path node[hlc] (0) at (0,0) {0} ; % Done with path but not with the loop
node[hlc] (1) at (1,1) {1} ;
node[hlc] (2) at (2,2) {2} ;


While effectively this shouldn't cause an error, it does when it is inside the loop. The path ends after the loop is finished hence the semicolon belongs outside the braces

\begin{tikzpicture}
[
hlc/.style={circle,inner sep=5,draw}
]
\def\odl{0,...,7}
\path foreach \x in \odl { node[hlc] (\x) at (\x,\x) {\x} };
\end{tikzpicture}


• Is the ; after the \def line even necessary? (I know the OP also had it) – daleif Aug 25 '16 at 14:16
• Thanks a lot @percusse. I did not know that that the ; after the \def command would make such a big difference. Your contribution has been to be very helpful. Cheers! – user24098 Aug 25 '16 at 14:58
• @daleif My mistake I forgot – percusse Aug 25 '16 at 15:35
• @user24098 That's my mistake. I'm talking about the ; inside the loop not after \def. That's unnecessary – percusse Aug 25 '16 at 15:36