# Defining a variable in terms of another variable

This is a very elementary question, I hope it is still OK to ask it here.

I'd like to do the following

    \documentclass{article}
\usepackage{tikz}

\begin{tikzpicture}

\def \x {2}
\def \y {\x + 2}

\foreach \s in {\x,...,\y}
{
% Do things
}

\end{tikzpicture}


This gives me the error

    ! Illegal unit of measure (pt inserted).
+
1.12 }


Why is this not possible?

-

TeX doesn't parse math as you want it to do. Here, \foreach might be flexible enough to understand it but in general it is a bad idea.

You can force it via PGF math such as

\pgfmathsetmacro\x{2}
\pgfmathsetmacro\y{int(\x + 2)} %without int \y would be 4.0 instead of 4

\foreach \s in {\x,...,\y}
{
% Do things
}

-

This is an expansion issue. When you use \def\y{...} \y takes the value that {....} has at the time of use, not at the time the definition was made.

Assuming that you're working with integer values, what you want is probably something like

\edef\y{\number\numexpr\x+2\relax}

-

The tikz way of assigning a value to a macro (\y, here) using that of another macro (\x, here) is to use

• \pgfmathsetmacro (\y's value is then a fixed-point number), or
• \pgfmathtruncatemacro (for an integer value).

Here is an example.

\documentclass{article}
\usepackage{tikz}

\begin{document}

\def\x{2}
\pgfmathsetmacro\xii{\x+0.25*\x}
\pgfmathsetmacro\y{\x+4.5}

\foreach \s in {\x,\xii,...,\y}{\s,\ }

\end{document}

-

A recommended solution with fp.

\documentclass[tikz,border=12pt,12pt]{standalone}
\usepackage[nomessages]{fp}
\FPset\x{2}
\FPeval\y{x+2}

\begin{document}
\begin{tikzpicture}

\foreach \s in {\x,...,\y}
{
% Do things
\draw (\s,\s) node {\s};
}

\end{tikzpicture}
\end{document}


-