GeneralBest of two tests for empty argument

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
woj-k
Posts: 15
Joined: Wed Jul 28, 2010 7:25 pm

Best of two tests for empty argument

Post by woj-k »

Hi everyone,

I'm recently using a lot of macros that have to check if an argument is supplied empty (usually an optional argument, but I don't suppose that matters). In other people's code I noticed two typical ways of doing it in plain LaTeX.

Code: Select all

\documentclass{minimal}

\newcommand*{\detokenizetest}[1][]{\if\relax\detokenize{#1}\relax Empty.\else Not empty.\fi}
\newcommand*{\emptytest}[1][]{\def\optional{#1}\ifx\optional\empty Empty.\else Not empty.\fi}

\begin{document}
\detokenizetest[]

\emptytest[]

\detokenizetest[foo]

\emptytest[foo]
\end{document}
My question is: is there any way in which one of the above is superior to the other, or could either fail in certain circumstances? Is \ifx effectively a shorthand for \if and \detokenize{}, or do I have this all wrong in my head?

Many thanks for any advice! (and happy holidays)

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org
LaTeX Beginner's Guide LaTeX Cookbook LaTeX TikZ graphics TikZによるLaTeXグラフィックス
User avatar
Johannes_B
Site Moderator
Posts: 4182
Joined: Thu Nov 01, 2012 4:08 pm

Re: Best of two tests for empty argument

Post by Johannes_B »

Package etoolbox provides some general facilities for testing, package xparse provides a few flags to test if an argument is empty. Xparse is used to define interfaces for user commands.


Really depends on what you are trying to do in the end.
The smart way: Calm down and take a deep breath, read posts and provided links attentively, try to understand and ask if necessary.
josephwright
Site Moderator
Posts: 814
Joined: Tue Jul 01, 2008 2:19 pm

Best of two tests for empty argument

Post by josephwright »

Test using \detokenize is expandable and therefore more general.
Joseph Wright
Post Reply