The ifthen package
Provides the conditional \ifthenelse{test}{true}{false} with tests for numbers, strings, lengths and flags, and the loop \whiledo.
Loading the package
\usepackage{ifthen}The package is the classic way to write a condition in a LaTeX document, for example a command that prints different text depending on its argument, or a document with a switch for solutions.
The test compares two numbers with <, = or >, two strings with \equal, or two lengths with \lengthtest. Tests are combined with \AND, \OR and \NOT, and grouped with \( and \).
The package is part of the LaTeX base distribution. For new code etoolbox is an alternative with more tests whose commands do not break in moving arguments.
Main commands
\ifthenelse{#1 < 50}{failed}{passed} | Compares two whole numbers. |
\ifthenelse{\equal{#1}{de}}{Deutsch}{English} | Compares two strings after expanding them. |
\ifthenelse{\value{page} > 1}{...}{...} | \value{counter} puts the value of a counter into a number test. |
\newboolean{solutions}, \setboolean{solutions}{true} | Creates and sets a flag. |
\ifthenelse{\boolean{solutions}}{...}{...} | Tests a flag. |
\ifthenelse{\lengthtest{\textwidth > 10cm}}{...}{...} | Compares two lengths. |
\ifthenelse{\isodd{\pageref{sec:a}}}{...}{...} | Tests whether a number is odd, here the page of a label. |
\whiledo{\value{row} < 3}{\stepcounter{row}...} | Repeats the body as long as the test is true. |
Complete example
\documentclass{article}
\usepackage{ifthen}
\newboolean{solutions}
\setboolean{solutions}{true}
\newcommand{\grade}[1]{\ifthenelse{#1 < 50}{failed}{passed}}
\newcommand{\langname}[1]{\ifthenelse{\equal{#1}{de}}{Deutsch}{English}}
\newcounter{row}
\begin{document}
40 points: \grade{40}. 70 points: \grade{70}. Language: \langname{de}.
Exercise 1: What is $6 \cdot 7$?
\ifthenelse{\boolean{solutions}}{Solution: 42.}{}
\whiledo{\value{row} < 3}{\stepcounter{row}Row \arabic{row}. }
\end{document}Compiled with pdfLaTeX from TeX Live 2023.
Pitfalls
\ifthenelseis fragile. In\section{...}or\caption{...}it stops with errors unless\protectstands in front of it.\isodd{\value{page}}can give the wrong answer near a page break, because LaTeX decides where the page ends after it has read the text. Set a\labelat the place and test\isodd{\pageref{...}}; the result is right from the second run on.- Number tests accept whole numbers only;
1.5 < 2stops with Missing number, treated as zero. Compare lengths with\lengthtest.
Related pages
- How-to Define your own commands in LaTeX
- How-to Counters in LaTeX
- Package
etoolbox - Package
calc