Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I feel really stupid for asking this, but how do you form more complex if conditionals in TeX? I'm looking for something like:

\ifnum\x=1 OR \ifnum\x=14
    {do this}
\else
    {do that}
\fi

I don't want to have to resort to copy-pasting the entire condition just to change the expression when the body is the same.

share|improve this question
    
The `` syntax doesn't work great in titles. –  ℝaphink Sep 29 '11 at 12:31
    
@Raphink: Ah, sorry, didn't know that. –  gablin Sep 29 '11 at 12:36
    
also LaTeX conditional expression –  Leo Liu Sep 29 '11 at 16:35

2 Answers 2

up vote 22 down vote accepted

There are a number of approaches. Assuming you are looking for a purely primitive-based on, then something like

\ifnum\ifnum\x=1 1\else\ifnum\x=14 1\else0\fi\fi
   =1 %
  {do this}
 \else
   {do that}
 \fi

Thus you use 'secondary' conditionals to convert the original problem into a simple TRUE/FALSE situation, where the 'outer' \ifnum is simply testing for 0 or 1. (This works as TeX keeps expanding until it finds a number when considering the outer \ifnum.)

It's important to get the number-termination correct when using this approach. In the example, the spaces after \x=1 and \x=14 are required to get the correct outcome. With a bit more imagination, you can make more complex constructs using the same approach (for example, you can having combined OR and AND conditions in this way.)

An alternative method if the logic gets complex would be to include the 'payload' as separate macros:

\ifnum\x=1 %
  \expandafter\myfirstcase
\else
  \ifnum\x=14 %
    \expandafter\expandafter\expandafter\myfirstcase
  \else
    \expandafter\expandafter\expandafter\mysecondcase
  \fi
\fi
\def\myfirstcase{do this}
\def\mysecondcase{do that}

This is what you often see with larger 'to do' blocks. The \expandafter use is 'good practice' but may not be needed depending on the exact nature of the code to insert.

share|improve this answer
2  
Yes, TeX is Turing-complete, but... –  ℝaphink Sep 29 '11 at 12:27
4  
@Raphink There are alternative, logic-based, approaches. However, the question says tex-core, so I went with a pure primitive approach. (I'd personally use LaTeX3's \bool_if:nTF.) –  Joseph Wright Sep 29 '11 at 12:28
    
@GonzaloMedina Fixed, thanks –  Joseph Wright Sep 29 '11 at 13:49
\usepackage{etoolbox}

\newcommand{\mytest}[1]{%
  \ifboolexpr{ test {\ifnumcomp{#1}{=}{1}} or test {\ifnumcomp{#1}{=}{14}} }
    {do this}
    {do that}}

\mytest{1} \mytest{14} \mytest{0}

There is also the xifthen package that provides for "composite" tests.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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