8

I am trying to learn to work with numexpr and am having some trouble with the basics, and etex_man has not been detailed enough to help in this case.

Here is an MWE:

\documentclass{article}
\begin{document}
Hi \numexpr 6 + 1 \relax
\end{document}

The error when I call pdflatex from TexLive 2018 is "You can't use `\numexpr' in horizontal mode. Hi \numexpr." Similar error if I switch to vertical or math mode.

So clearly I am missing something basic. Could someone enlighten me?

Thanks in advance

  • 2
    You might want to read Chapter 7 of TeX by Topic which explains the different number types in TeX and in what context they may occur. \numexpr is added in e-TeX as a new alternative to <internal integer>. You find the extended grammar rules in the e-TeX manual. – siracusa May 27 at 19:50
10

\numexpr is an additional item that can be used in contexts where TeX is looking for a <number>.

It basically is an “unnamed counter register” as far as its syntax is concerned and is not allowed “bare”.

It essentially works like \countX (where \countX stands for an “unreachable” count register number) after this unnamed register is loaded with the value of the expression.

So just like you can't say Hi \count232 to print the value stored in \count232, you cannot say

Hi \numexpr 6+1\relax

Just consider \count232 and \numexpr 6+1\relax as referring to an abstract number, which exists independently of its representation. You need to access a representation of this abstract number:

Hi \number\count232

Hi \romannumeral\count232

Hi \number\numexpr 6+1\relax

Hi \romannumeral\numexpr 6+1\relax

Bare bones TeX only provides \number (for the decimal representation) and \romannumeral (for lowercase Roman numeral representation). Add-on packages may provide other representations.

9

You need \number or \the in front of the expression: \numexpr works like a TeX \count. Alternatively, you could use the xfp package to provide a thin wrapper

\documentclass{article}
\usepackage{xfp}
\begin{document}

\number\numexpr 1 + 2 * 3 \relax

\the\numexpr 1 + 2 * 3 \relax

\inteval{1 + 2 * 3}

\end{document}
  • Thanks--this certainly removed the error. Do you know why this is needed? I am not a TeX wiz, and Googling "the TeX" is unproductive... – Zach Boyd May 27 at 19:12
  • 2
    @ZachBoyd Some commands are just not meant to be used in horizontal mode (typesetting): \numexpr is just one of those. – Joseph Wright May 27 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.