Calculate length in \newlength with \dimexpr

lengthstex-core

\documentclass[a4paper]{article}
\usepackage{geometry}
\geometry{showframe}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\begin{document}
(1)

    \newlength{\ccc}{\dimexpr\textwidth-100pt}

% This cause error message: You can't use `\dimexpr' in vertical mode.Why is \dimexpr used here a wrong way?

(2)

    \newdimen\ddd{\dimexpr\textwidth-100pt}

% This also causes error.

(3)

        \def\aaa{\dimexpr\textwidth-100pt}
    
    \rule{\aaa}{10pt}

% This does work.
\end{document}

I'm confused. Does that mean length calculation can not be done by \dimexpr in \newlength?

Best Answer

Your example (2): \newdimen has only one parameters, it declares a new "dimen" variable and sets it to 0pt. It has only one parameter (\ddd in your example). The following {\dimexpr ...} opens a group { and sees \dimexpr in vertical mode. TeX does not allow to use \dimexpr in this context. You can use \the\dimexpr... to print the value, but not \dimexpr alone. TeX reports the error.

Your example (3): you define macro (no variable) \aaa and it expands to \dimexpr.... You use this macro in the context \hrule height\aaa wich expands to \hrule height\dimexpr.... Now the \dimexpr is used in allowed context.