I have recently come across a problem while creating a LaTeX style (for making A0-size posters). Maybe it could be avoided or solved more elegantly, but I wanted to solve it with conditionals.
Basically, what I wanted to do was define a command (actually, an environment) that accepted one argument, and make it return different output, depending on the argument:
if (argument equals something) then
do something
else
do somethingelse
end if
It gave me some headaches to get it, but I also learned some interesting things on the way. There are at least two ways of playing with conditionals: defining boolean variables or directly using logical comparisons.
Defining logical valiables
We can define a logical variable logvar as follows:
\newif\iflogvar
By default, it is set to false. We can set it to true by:
\logvartrue
and back to false by:
\logvarfalse
The variable can be used in a conditional as follows:
\iflogvar
aaaa
\else
bbbb
\fi
You can think of the above code as a single object, the output value of which will be “aaaa” if logvar is true, and “bbbb” if false. Basically, the following code will, thus, output “Today is great“:
Today
\newif\ifismonday
\ismondayfalse
\ifismonday
sucks!
\else
is \textbf{great}
\fi
Direct logic comparison
The example I provide works for numbers, but check this page for more info. Recall that LaTeX works with integers (counters) and text strings. As far as I know, floating point operations are impossible in LaTeX (nothing is actually impossible in LaTeX, just veeery difficult).
For example, defining the following command in the preamble:
\newcommand{\isitthree}[1]
{
\ifnum#1=3
number #1 is 3
\else
number #1 is not 3
\fi
}
allows us to call it in the document, so the following outputs “We know that number 33 is not 3”:
We know that \isitthree{33}
Nesting
Obviously the conditionals can be nested (put one inside another), when more than one condition needs to be tested. For example:
Today
\newif\ifismonday
\newif\ifistuesday
\ismondayfalse
\istuesdaytrue
\ifismonday
sucks!
\else
\ifistuesday
almost sucks.
\else
is \textbf{great}
\fi
\fi