3

I'm reading in a number (as text) from the aux file and I want to do a numerical test (\ifnum) on it. I can to it using \setcounter and \value, but I really don't want to create a counter just to do a lousy test. Is there a simpler way?

Using pgfmath is not by any stretch of the imagination simpler.

\documentclass{article}
\newcount\test
\newcounter{test}
\begin{document}

\def\temp{1}

\setcounter{test}{\temp}
\ifnum\value{test}>0 Yea!
\else Boo!
\fi

\test=\temp
\ifnum\test>0 Yea!
\else Boo!
\fi

\end{document}

In retrospect, my mistake is obvious. In an expression like

\test=1

the end-of-line terminates both adding digits and conversion of "1" to a count. But with

\test=\temp

the end-of-line is consumed terminating the macro name. I suspect that the final expansion of this is actually

\test=1 Boo!

which is legal but too late. The simplest solution

\test=\temp\relax

uses \relax to force the expression to completion.

John Kormylo
  • 79,712
  • 3
  • 50
  • 120

1 Answers1

5

As I indicated in my comment, you can dispense with the counters. Just use the \def as an argument. If you need a more complex calculation, you can use \numexpr, as in my 2nd example.

\documentclass{article}
\begin{document}

\def\temp{1}
\def\X{2}

\ifnum\temp>0 Yea!
\else Boo!
\fi

\ifnum\numexpr\temp-\X\relax>0 Yea!
\else Boo!
\fi

\end{document}

enter image description here


To follow up with the OP's comment about difficulty of mixing tokens and counters, I will post this MWE that works with that mix:

\documentclass{article}
\newcounter{mycount}
\setcounter{mycount}{0}
\begin{document}
\def\temp{1}
\ifnum\value{mycount}>\temp Yea!
\else Boo!
\fi
\end{document}
  • \numexpr is what I was looking for, but most surprising was that you can use \ifnum to compare two strings or two counts, but not a string and a count. – John Kormylo Dec 17 '14 at 01:30
  • @JohnKormylo You can do \newcounter{mycount}\setcounter{mycount}{0}\ifnum\themycount>\temp... or \ifnum\value{mycount}>\temp... – Steven B. Segletes Dec 17 '14 at 01:38
  • \ifnum\value{mycount}>\temp doesn't work, or at least I've been having problems with it all day. – John Kormylo Dec 17 '14 at 01:55
  • @JohnKormylo Well I noticed your MWE had \newcount\test, rather that \newcounter{test}. Perhaps that could account for it. I tested my comment before posting. Please see revision. – Steven B. Segletes Dec 17 '14 at 02:01
  • Actually, I had both (\c@test does not conflict with \test). Anyway, it looks like my problem was due to something else altogether, and I may wind up deleting this question as irrelevant. – John Kormylo Dec 17 '14 at 02:08