Optional Arguments in LaTeX Macros

As I’ve mentioned before, I use LaTeX to typeset my resume. I recently found a convenient workaround to handle formatting which differs based on whether or not a macro’s argument is present.

The solution to testing whether a given macro argument is empty is buried deep within the LaTeX community forums:

\newcommand{\maybe}[2]{
    \ifx&#1&
        Argument 1 was blank!
    \else
        Argument 1 was not blank.
    \fi
    Argument 2 was #2.
}

The LaTeX wikibook goes into more detail on the ifx command. It appears that &#1 is interpereted as a macro for purposes of equality comparison, then compared against the ``& `` empty macro.

The wikibook’s TeX category discusses a variety of other if commands. Of particular interest is the ifnum command, which tests whether a value is equal to a given integer.